Wagtail is an open source CMS written in Python and built on the Django web framework. Below are some useful links to help you get started with Wagtail. If you’d like to get a quick feel for Wagtail, try spinning up a temporary developer environment in your browser (running on Gitpod - here’s how it works). • First steps – Getting started – Your first Wagtail site – Demo site • Using Wagtail – Page models – Writing templates – How to use images in templates – Search – Third-party tutorials • For editors – Editors guide
Contents 1 Wagtail Documentation, Release 2.15a0
2 Contents CHAPTER 1
Index
1.1 Getting started
Note: These instructions assume familiarity with virtual environments and the Django web framework. For more detailed instructions, see Your first Wagtail site. To add Wagtail to an existing Django project, see Integrating Wagtail into a Django project.
1.1.1 Dependencies needed for installation
• Python 3 • libjpeg and zlib, libraries required for Django’s Pillow library. See Pillow’s platform-specific installation in- structions.
1.1.2 Quick install
Run the following in a virtual environment of your choice:
$ pip install wagtail
(Installing outside a virtual environment may require sudo.) Once installed, Wagtail provides a command similar to Django’s django-admin startproject to generate a new site/project:
$ wagtail start mysite
This will create a new folder mysite, based on a template containing everything you need to get started. More information on that template is available in the project template reference. Inside your mysite folder, run the setup steps necessary for any Django project:
Your site is now accessible at http://localhost:8000, with the admin backend available at http:// localhost:8000/admin/. This will set you up with a new stand-alone Wagtail project. If you’d like to add Wagtail to an existing Django project instead, see Integrating Wagtail into a Django project. There are a few optional packages which are not installed by default but are recommended to improve performance or add features to Wagtail, including: • Elasticsearch. • Feature Detection.
Your first Wagtail site
Note: This tutorial covers setting up a brand new Wagtail project. If you’d like to add Wagtail to an existing Django project instead, see Integrating Wagtail into a Django project.
Install and run Wagtail
Install dependencies
Wagtail supports Python 3.6, 3.7, 3.8 and 3.9. To check whether you have an appropriate version of Python 3:
$ python3 --version
If this does not return a version number or returns a version lower than 3.6, you will need to install Python 3.
Important: Before installing Wagtail, it is necessary to install the libjpeg and zlib libraries, which provide support for working with JPEG, PNG and GIF images (via the Python Pillow library). The way to do this varies by platform—see Pillow’s platform-specific installation instructions.
Create and activate a virtual environment
We recommend using a virtual environment, which isolates installed dependencies from other projects. This tutorial uses venv, which is packaged with Python 3. On Windows (cmd.exe):
Note: If you’re using version control (e.g. git), mysite will be the directory for your project. The env directory inside of it should be excluded from any version control.
Install Wagtail
Use pip, which is packaged with Python, to install Wagtail and its dependencies:
$ pip install wagtail
Generate your site
Wagtail provides a start command similar to django-admin startproject. Running wagtail start mysite in your project will generate a new mysite folder with a few Wagtail-specific extras, including the required project settings, a “home” app with a blank HomePage model and basic templates, and a sample “search” app. Because the folder mysite was already created by venv, run wagtail start with an additional argument to specify the destination directory:
$ wagtail start mysite mysite
Note: Generally, in Wagtail, each page type, or content type, is represented by a single app. However, differ- ent apps can be aware of each other and access each other’s data. All of the apps need to be registered within the INSTALLED_APPS section of the settings file. Look at this file to see how the start command has listed them in there.
Install project dependencies
$ cd mysite $ pip install -r requirements.txt
This ensures that you have the relevant versions of Wagtail, Django, and any other dependencies for the project you have just created.
Create the database
If you haven’t updated the project settings, this will be a SQLite database file in the project directory.
$ python manage.py migrate
This command ensures that the tables in your database are matched to the models in your project. Every time you alter your model (eg. you may add a field to a model) you will need to run this command in order to update the database.
1.1. Getting started 5 Wagtail Documentation, Release 2.15a0
Create an admin user
$ python manage.py createsuperuser
When logged into the admin site, a superuser has full permissions and is able to view/create/manage the database.
Start the server
$ python manage.py runserver
If everything worked, http://127.0.0.1:8000 will show you a welcome page:
You can now access the administrative area at http://127.0.0.1:8000/admin
6 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Extend the HomePage model
Out of the box, the “home” app defines a blank HomePage model in models.py, along with a migration that creates a homepage and configures Wagtail to use it. Edit home/models.py as follows, to add a body field to the model:
from django.db import models
from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class HomePage(Page): body= RichTextField(blank= True)
(continues on next page)
1.1. Getting started 7 Wagtail Documentation, Release 2.15a0
(continued from previous page) content_panels= Page.content_panels+[ FieldPanel('body', classname="full"), ]
body is defined as RichTextField, a special Wagtail field. When blank=True, it means that this field is not required and can be empty. You can use any of the Django core fields. content_panels define the capabilities and the layout of the editing interface. When you add fields to content_panels, it enables them to be edited on the Wagtail interface. More on creating Page models. Run python manage.py makemigrations (this will create the migrations file), then python manage.py migrate (this executes the migrations and updates the database with your model changes). You must run the above commands each time you make changes to the model definition. You can now edit the homepage within the Wagtail admin area (go to Pages, Homepage, then Edit) to see the new body field. Enter some text into the body field, and publish the page by selecting Publish at the bottom of the page editor, rather than Save Draft. The page template now needs to be updated to reflect the changes made to the model. Wagtail uses normal Django tem- plates to render each page type. By default, it will look for a template filename formed from the app and model name, separating capital letters with underscores (e.g. HomePage within the ‘home’ app becomes home/home_page. html). This template file can exist in any location recognised by Django’s template rules; conventionally it is placed under a templates folder within the app. Edit home/templates/home/home_page.html to contain the following:
base.html refers to a parent template and must always be the first template tag used in a template. Extending from this template saves you from rewriting code and allows pages across your app to share a similar frame (by using block tags in the child template, you are able to override specific content within the parent template). wagtailcore_tags must also be loaded at the top of the template and provide additional tags to those provided by Django.
8 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Wagtail template tags
In addition to Django’s template tags and filters, Wagtail provides a number of its own template tags & filters which can be loaded by including {% load wagtailcore_tags %} at the top of your template file. In this tutorial, we use the richtext filter to escape and print the contents of a RichTextField:
Note: You’ll need to include {% load wagtailcore_tags %} in each template that uses Wagtail’s tags. Django will throw a TemplateSyntaxError if the tags aren’t loaded.
A basic blog
We are now ready to create a blog. To do so, run python manage.py startapp blog to create a new app in your Wagtail site. Add the new blog app to INSTALLED_APPS in mysite/settings/base.py.
Blog Index and Posts
Lets start with a simple index page for our blog. In blog/models.py:
1.1. Getting started 9 Wagtail Documentation, Release 2.15a0
from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class BlogIndexPage(Page): intro= RichTextField(blank= True)
Run python manage.py makemigrations and python manage.py migrate. Since the model is called BlogIndexPage, the default template name (unless we override it) will be blog/ templates/blog/blog_index_page.html. Create this file with the following content:
Most of this should be familiar, but we’ll explain get_children a bit later. Note the pageurl tag, which is similar to Django’s url tag but takes a Wagtail Page object as an argument. In the Wagtail admin, create a BlogIndexPage as a child of the Homepage, make sure it has the slug “blog” on the Promote tab, and publish it. You should now be able to access the url /blog on your site (note how the slug from the Promote tab defines the page URL). Now we need a model and template for our blog posts. In blog/models.py: from django.db import models from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel from wagtail.search import index
# Keep the definition of BlogIndexPage, and add: class BlogPage(Page): date= models.DateField("Post date") (continues on next page)
10 Chapter 1. Index Wagtail Documentation, Release 2.15a0
(continued from previous page) intro= models.CharField(max_length=250) body= RichTextField(blank= True)
In the model above, we import index as this makes the model searchable. You can then list fields that you want to be searchable for the user. Run python manage.py makemigrations and python manage.py migrate. Create a template at blog/templates/blog/blog_page.html:
Note the use of Wagtail’s built-in get_parent() method to obtain the URL of the blog this post is a part of. Now create a few blog posts as children of BlogIndexPage. Be sure to select type “Blog Page” when creating your posts.
1.1. Getting started 11 Wagtail Documentation, Release 2.15a0
Wagtail gives you full control over what kinds of content can be created under various parent content types. By default, any page type can be a child of any other page type.
Publish each blog post when you are done editing. You should now have the very beginnings of a working blog. Access the /blog URL and you should see something like this:
12 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Titles should link to post pages, and a link back to the blog’s homepage should appear in the footer of each post page.
Parents and Children
Much of the work you’ll be doing in Wagtail revolves around the concept of hierarchical “tree” structures consisting of nodes and leaves (see Theory). In this case, the BlogIndexPage is a “node” and individual BlogPage instances are the “leaves”. Take another look at the guts of blog_index_page.html:
Every “page” in Wagtail can call out to its parent or children from its own position in the hierarchy. But why do we have to specify post.specific.intro rather than post.intro? This has to do with the way we defined our model: class BlogPage(Page): The get_children() method gets us a list of instances of the Page base class. When we want to reference properties of the instances that inherit from the base class, Wagtail provides the specific method that retrieves the actual BlogPage record. While the “title” field is present on the base Page model, “intro” is only present on the BlogPage model, so we need .specific to access it. To tighten up template code like this, we could use Django’s with tag:
1.1. Getting started 13 Wagtail Documentation, Release 2.15a0
{% for post in page.get_children %} {% with post=post.specific %}
When you start writing more customized Wagtail code, you’ll find a whole set of QuerySet modifiers to help you navigate the hierarchy.
# Given a page object 'somepage': MyModel.objects.descendant_of(somepage) child_of(page)/ not_child_of(somepage) ancestor_of(somepage)/ not_ancestor_of(somepage) parent_of(somepage)/ not_parent_of(somepage) sibling_of(somepage)/ not_sibling_of(somepage) # ... and ... somepage.get_children() somepage.get_ancestors() somepage.get_descendants() somepage.get_siblings()
For more information, see: Page QuerySet reference
Overriding Context
There are a couple of problems with our blog index view: 1. Blogs generally display content in reverse chronological order 2. We want to make sure we’re only displaying published content. To accomplish these things, we need to do more than just grab the index page’s children in the template. In- stead, we’ll want to modify the QuerySet in the model definition. Wagtail makes this possible via the overridable get_context() method. Modify your BlogIndexPage model like this:
class BlogIndexPage(Page): intro= RichTextField(blank= True)
def get_context(self, request): # Update context to include only published posts, ordered by reverse-chron context= super().get_context(request) blogpages= self.get_children().live().order_by('-first_published_at') context['blogpages']= blogpages return context
All we’ve done here is retrieve the original context, create a custom QuerySet, add it to the retrieved context, and return the modified context back to the view. You’ll also need to modify your blog_index_page.html template slightly. Change: {% for post in page.get_children %} to {% for post in blogpages %} Now try unpublishing one of your posts - it should disappear from the blog index page. The remaining posts should now be sorted with the most recently published posts first.
14 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Images
Let’s add the ability to attach an image gallery to our blog posts. While it’s possible to simply insert images into the body rich text field, there are several advantages to setting up our gallery images as a new dedicated object type within the database - this way, you have full control of the layout and styling of the images on the template, rather than having to lay them out in a particular way within the rich text field. It also makes it possible for the images to be used elsewhere, independently of the blog text - for example, displaying a thumbnail on the blog index page. Add a new BlogPageGalleryImage model to models.py: from django.db import models
# New imports added for ParentalKey, Orderable, InlinePanel, ImageChooserPanel from modelcluster.fields import ParentalKey from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel, InlinePanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index
# ... (Keep the definition of BlogIndexPage, and update BlogPage:) class BlogPage(Page): date= models.DateField("Post date") intro= models.CharField(max_length=250) body= RichTextField(blank= True)
Run python manage.py makemigrations and python manage.py migrate.
1.1. Getting started 15 Wagtail Documentation, Release 2.15a0
There are a few new concepts here, so let’s take them one at a time: Inheriting from Orderable adds a sort_order field to the model, to keep track of the ordering of images in the gallery. The ParentalKey to BlogPage is what attaches the gallery images to a specific page. A ParentalKey works similarly to a ForeignKey, but also defines BlogPageGalleryImage as a “child” of the BlogPage model, so that it’s treated as a fundamental part of the page in operations like submitting for moderation, and tracking revision history. image is a ForeignKey to Wagtail’s built-in Image model, where the images themselves are stored. This comes with a dedicated panel type, ImageChooserPanel, which provides a pop-up interface for choosing an existing image or uploading a new one. This way, we allow an image to exist in multiple galleries - effectively, we’ve created a many-to-many relationship between pages and images. Specifying on_delete=models.CASCADE on the foreign key means that if the image is deleted from the system, the gallery entry is deleted as well. (In other situations, it might be appropriate to leave the entry in place - for example, if an “our staff” page included a list of people with headshots, and one of those photos was deleted, we’d rather leave the person in place on the page without a photo. In this case, we’d set the foreign key to blank=True, null=True, on_delete=models.SET_NULL.) Finally, adding the InlinePanel to BlogPage.content_panels makes the gallery images available on the editing interface for BlogPage. Adjust your blog page template to include the images:
Here we use the {% image %} tag (which exists in the wagtailimages_tags library, imported at the top of the template) to insert an element, with a fill-320x240 parameter to indicate that the image should be resized and cropped to fill a 320x240 rectangle. You can read more about using images in templates in the docs.
16 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Since our gallery images are database objects in their own right, we can now query and re-use them independently of the blog post body. Let’s define a main_image method, which returns the image from the first gallery item (or None if no gallery items exist): class BlogPage(Page): date= models.DateField("Post date") intro= models.CharField(max_length=250) body= RichTextField(blank= True)
Let’s say we want to let editors “tag” their posts, so that readers can, e.g., view all bicycle-related content together. For this, we’ll need to invoke the tagging system bundled with Wagtail, attach it to the BlogPage model and content panels, and render linked tags on the blog post template. Of course, we’ll need a working tag-specific URL view as well. First, alter models.py once more: from django.db import models
# New imports added for ClusterTaggableManager, TaggedItemBase, MultiFieldPanel from modelcluster.fields import ParentalKey from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index
# ... (Keep the definition of BlogIndexPage) class BlogPageTag(TaggedItemBase): content_object= ParentalKey( 'BlogPage', related_name='tagged_items', on_delete=models.CASCADE ) (continues on next page)
18 Chapter 1. Index Wagtail Documentation, Release 2.15a0
(continued from previous page) class BlogPage(Page): date= models.DateField("Post date") intro= models.CharField(max_length=250) body= RichTextField(blank= True) tags= ClusterTaggableManager(through=BlogPageTag, blank= True)
# ... (Keep the main_image method and search_fields definition)
Run python manage.py makemigrations and python manage.py migrate. Note the new modelcluster and taggit imports, the addition of a new BlogPageTag model, and the addition of a tags field on BlogPage. We’ve also taken the opportunity to use a MultiFieldPanel in content_panels to group the date and tags fields together for readability. Edit one of your BlogPage instances, and you should now be able to tag posts:
To render tags on a BlogPage, add this to blog_page.html:
1.1. Getting started 19 Wagtail Documentation, Release 2.15a0
{% if page.tags.all.count %}
Tags
{% for tag in page.tags.all %} {% endfor %}
{% endif %}
Notice that we’re linking to pages here with the builtin slugurl tag rather than pageurl, which we used earlier. The difference is that slugurl takes a Page slug (from the Promote tab) as an argument. pageurl is more com- monly used because it is unambiguous and avoids extra database lookups. But in the case of this loop, the Page object isn’t readily available, so we fall back on the less-preferred slugurl tag. Visiting a blog post with tags should now show a set of linked buttons at the bottom - one for each tag. However, clicking a button will get you a 404, since we haven’t yet defined a “tags” view. Add to models.py:
class BlogTagIndexPage(Page):
def get_context(self, request):
# Filter by tag tag= request.GET.get('tag') blogpages= BlogPage.objects.filter(tags__name=tag)
Note that this Page-based model defines no fields of its own. Even without fields, subclassing Page makes it a part of the Wagtail ecosystem, so that you can give it a title and URL in the admin, and so that you can manipulate its contents by returning a QuerySet from its get_context() method. Migrate this in, then create a new BlogTagIndexPage in the admin. You’ll probably want to create the new page/view as a child of Homepage, parallel to your Blog index. Give it the slug “tags” on the Promote tab. Access /tags and Django will tell you what you probably already knew: you need to create a template blog/ blog_tag_index_page.html:
˓→strong> Revised: {{ blogpage.latest_revision_created_at }} {% if blogpage.author %}
By {{ blogpage.author.profile }}
(continues on next page)
20 Chapter 1. Index Wagtail Documentation, Release 2.15a0
(continued from previous page) {% endif %}
{% empty %} No pages found with that tag. {% endfor %}
{% endblock %}
We’re calling the built-in latest_revision_created_at field on the Page model - handy to know this is always available. We haven’t yet added an “author” field to our BlogPage model, nor do we have a Profile model for authors - we’ll leave those as an exercise for the reader. Clicking the tag button at the bottom of a BlogPost should now render a page something like this:
Categories
Let’s add a category system to our blog. Unlike tags, where a page author can bring a tag into existence simply by using it on a page, our categories will be a fixed list, managed by the site owner through a separate area of the admin interface. First, we define a BlogCategory model. A category is not a page in its own right, and so we define it as a standard Django models.Model rather than inheriting from Page. Wagtail introduces the concept of “snippets” for reusable pieces of content that need to be managed through the admin interface, but do not exist as part of the page tree themselves; a model can be registered as a snippet by adding the @register_snippet decorator. All the field types we’ve used so far on pages can be used on snippets too - here we’ll give each category an icon image as well as a name. Add to blog/models.py:
from wagtail.snippets.models import register_snippet
(continues on next page)
1.1. Getting started 21 Wagtail Documentation, Release 2.15a0
Note: Note that we are using panels rather than content_panels here - since snippets generally have no need for fields such as slug or publish date, the editing interface for them is not split into separate ‘content’ / ‘promote’ / ‘settings’ tabs as standard, and so there is no need to distinguish between ‘content panels’ and ‘promote panels’.
Migrate this change in, and create a few categories through the Snippets area which now appears in the admin menu. We can now add categories to the BlogPage model, as a many-to-many field. The field type we use for this is ParentalManyToManyField - this is a variant of the standard Django ManyToManyField which ensures that the chosen objects are correctly stored against the page record in the revision history, in much the same way that ParentalKey replaces ForeignKey for one-to-many relations.
# New imports added for forms and ParentalManyToManyField from django import forms from django.db import models from modelcluster.fields import ParentalKey, ParentalManyToManyField from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase
Here we’re making use of the widget keyword argument on the FieldPanel definition to specify a checkbox- based widget instead of the default multiple select box, as this is often considered more user-friendly. Finally, we can update the blog_page.html template to display the categories:
{{ page.title }}
{{ page.date }}
{% with categories=page.categories.all %} {% if categories %}
1.1. Getting started 23 Wagtail Documentation, Release 2.15a0
Where next
• Read the Wagtail topics and reference documentation • Learn how to implement StreamField for freeform page content • Browse through the advanced topics section and read third-party tutorials
Demo site
To create a new site on Wagtail we recommend the wagtail start command in Getting started. We also have a demo site, The Wagtail Bakery, which contains example page types and models. We recommend you use the demo site for testing during development of Wagtail itself. The source code and installation instructions can be found at https://github.com/wagtail/bakerydemo
Integrating Wagtail into a Django project
Wagtail provides the wagtail start command and project template to get you started with a new Wagtail project as quickly as possible, but it’s easy to integrate Wagtail into an existing Django project too. Wagtail is currently compatible with Django 3.0, 3.1 and 3.2. First, install the wagtail package from PyPI:
$ pip install wagtail
24 Chapter 1. Index Wagtail Documentation, Release 2.15a0
or add the package to your existing requirements file. This will also install the Pillow library as a dependency, which requires libjpeg and zlib - see Pillow’s platform-specific installation instructions.
Settings
In your settings file, add the following apps to INSTALLED_APPS:
Add a WAGTAIL_SITE_NAME - this will be displayed on the main dashboard of the Wagtail admin backend:
WAGTAIL_SITE_NAME='My Example Site'
Various other settings are available to configure Wagtail’s behaviour - see Settings.
URL configuration
Now make the following additions to your urls.py file:
from django.urls import path, include
from wagtail.admin import urls as wagtailadmin_urls from wagtail.core import urls as wagtail_urls from wagtail.documents import urls as wagtaildocs_urls
urlpatterns=[ ... path('cms/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), (continues on next page)
1.1. Getting started 25 Wagtail Documentation, Release 2.15a0
(continued from previous page) path('pages/', include(wagtail_urls)), ... ]
The URL paths here can be altered as necessary to fit your project’s URL scheme. wagtailadmin_urls provides the admin interface for Wagtail. This is separate from the Django admin interface (django.contrib.admin); Wagtail-only projects typically host the Wagtail admin at /admin/, but if this would clash with your project’s existing admin backend then an alternative path can be used, such as /cms/ here. wagtaildocs_urls is the location from where document files will be served. This can be omitted if you do not intend to use Wagtail’s document management features. wagtail_urls is the base location from where the pages of your Wagtail site will be served. In the above example, Wagtail will handle URLs under /pages/, leaving the root URL and other paths to be handled as normal by your Django project. If you want Wagtail to handle the entire URL space including the root URL, this can be replaced with:
path('', include(wagtail_urls)),
In this case, this should be placed at the end of the urlpatterns list, so that it does not override more specific URL patterns. Finally, your project needs to be set up to serve user-uploaded files from MEDIA_ROOT. Your Django project may already have this in place, but if not, add the following snippet to urls.py:
from django.conf import settings from django.conf.urls.static import static urlpatterns=[ # ... the rest of your URLconf goes here ... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Note that this only works in development mode (DEBUG = True); in production, you will need to configure your web server to serve files from MEDIA_ROOT. For further details, see the Django documentation: Serving files up- loaded by a user during development and Deploying static files. With this configuration in place, you are ready to run ./manage.py migrate to create the database tables used by Wagtail.
User accounts
Superuser accounts receive automatic access to the Wagtail admin interface; use ./manage.py createsuperuser if you don’t already have one. Custom user models are supported, with some restric- tions; Wagtail uses an extension of Django’s permissions framework, so your user model must at minimum inherit from AbstractBaseUser and PermissionsMixin.
Start developing
You’re now ready to add a new app to your Django project (via ./manage.py startapp - remember to add it to INSTALLED_APPS) and set up page models, as described in Your first Wagtail site. Note that there’s one small difference when not using the Wagtail project template: Wagtail creates an initial homepage of the basic type Page, which does not include any content fields beyond the title. You’ll probably want to replace this with your own HomePage class - when you do so, ensure that you set up a site record (under Settings / Sites in the Wagtail admin) to point to the new homepage.
26 Chapter 1. Index Wagtail Documentation, Release 2.15a0
The Zen of Wagtail
Wagtail has been born out of many years of experience building websites, learning approaches that work and ones that don’t, and striking a balance between power and simplicity, structure and flexibility. We hope you’ll find that Wagtail is in that sweet spot. However, as a piece of software, Wagtail can only take that mission so far - it’s now up to you to create a site that’s beautiful and a joy to work with. So, while it’s tempting to rush ahead and start building, it’s worth taking a moment to understand the design principles that Wagtail is built on. In the spirit of “The Zen of Python”, The Zen of Wagtail is a set of guiding principles, both for building websites in Wagtail, and for the ongoing development of Wagtail itself.
Wagtail is not an instant website in a box.
You can’t make a beautiful website by plugging off-the-shelf modules together - expect to write code.
Always wear the right hat.
The key to using Wagtail effectively is to recognise that there are multiple roles involved in creating a website: the content author, site administrator, developer and designer. These may well be different people, but they don’t have to be - if you’re using Wagtail to build your personal blog, you’ll probably find yourself hopping between those different roles. Either way, it’s important to be aware of which of those hats you’re wearing at any moment, and to use the right tools for that job. A content author or site administrator will do the bulk of their work through the Wagtail admin interface; a developer or designer will spend most of their time writing Python, HTML or CSS code. This is a good thing: Wagtail isn’t designed to replace the job of programming. Maybe one day someone will come up with a drag- and-drop UI for building websites that’s as powerful as writing code, but Wagtail is not that tool, and does not try to be. A common mistake is to push too much power and responsibility into the hands of the content author and site admin- istrator - indeed, if those people are your clients, they’ll probably be loudly clamouring for exactly that. The success of your site depends on your ability to say no. The real power of content management comes not from handing control over to CMS users, but from setting clear boundaries between the different roles. Amongst other things, this means not having editors doing design and layout within the content editing interface, and not having site administrators building complex interaction workflows that would be better achieved in code.
A CMS should get information out of an editor’s head and into a database, as efficiently and directly as possible.
Whether your site is about cars, cats, cakes or conveyancing, your content authors will be arriving at the Wagtail admin interface with some domain-specific information they want to put up on the website. Your aim as a site builder is to extract and store this information in its raw form - not one particular author’s idea of how that information should look. Keeping design concerns out of page content has numerous advantages. It ensures that the design remains consistent across the whole site, not subject to the whims of editors from one day to the next. It allows you to make full use of the informational content of the pages - for example, if your pages are about events, then having a dedicated “Event” page type with data fields for the event date and location will let you present the events in a calendar view or filtered listing, which wouldn’t be possible if those were just implemented as different styles of heading on a generic page. Finally, if you redesign the site at some point in the future, or move it to a different platform entirely, you can be confident that the site content will work in its new setting, and not be reliant on being formatted a particular way. Suppose a content author comes to you with a request: “We need this text to be in bright pink Comic Sans”. Your question to them should be “Why? What’s special about this particular bit of text?” If the reply is “I just like the look of it”, then you’ll have to gently persuade them that it’s not up to them to make design choices. (Sorry.) But if the answer is “it’s for our Children’s section”, then that gives you a way to divide the editorial and design concerns: give
1.1. Getting started 27 Wagtail Documentation, Release 2.15a0 your editors the ability to designate certain pages as being “the Children’s section” (through tagging, different page models, or the site hierarchy) and let designers decide how to apply styles based on that.
The best user interface for a programmer is usually a programming language.
A common sight in content management systems is a point-and-click interface to let you define the data model that makes up a page:
It looks nice in the sales pitch, but in reality, no CMS end-user can realistically make that kind of fundamental change - on a live site, no less - unless they have a programmer’s insight into how the site is built, and what impact the change will have. As such, it will always be the programmer’s job to negotiate that point-and-click interface - all you’ve done is taken them away from the comfortable world of writing code, where they have a whole ecosystem of tools, from text editors to version control systems, to help them develop, test and deploy their code changes. Wagtail recognises that most programming tasks are best done by writing code, and does not try to turn them into box- filling exercises when there’s no good reason to. Likewise, when building functionality for your site, you should keep in mind that some features are destined to be maintained by the programmer rather than a content editor, and consider whether making them configurable through the Wagtail admin is going to be more of a hindrance than a convenience. For example, Wagtail provides a form builder to allow content authors to create general-purpose data collection forms. You might be tempted to use this as the basis for more complex forms that integrate with (for example) a CRM system or payment processor - however, in this case there’s no way to edit the form fields without rewriting the backend logic, so making them editable through Wagtail has limited value. More likely, you’d be better off building these using Django’s form framework, where the form fields are defined entirely in code.
1.2 Usage guide
1.2.1 Page models
Each page type (a.k.a. content type) in Wagtail is represented by a Django model. All page models must inherit from the wagtail.core.models.Page class.
28 Chapter 1. Index Wagtail Documentation, Release 2.15a0
As all page types are Django models, you can use any field type that Django provides. See Model field reference for a complete list of field types you can use. Wagtail also provides wagtail.core.fields.RichTextField which provides a WYSIWYG editor for editing rich-text content.
Note: If you’re not yet familiar with Django models, have a quick look at the following links to get you started: • Creating models • Model syntax
An example Wagtail page model
This example represents a typical blog post: from django.db import models from modelcluster.fields import ParentalKey from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index class BlogPage(Page):
Note: Ensure that none of your field names are the same as your class names. This will cause errors due to the way Django handles relations (read more). In our examples we have avoided this by appending “Page” to each model name.
Writing page models
Here we’ll describe each section of the above example to help you create your own page models.
Database fields
Each Wagtail page type is a Django model, represented in the database as a separate table. Each page type can have its own set of fields. For example, a news article may have body text and a published date, whereas an event page may need separate fields for venue and start/finish times. In Wagtail, you can use any Django field class. Most field classes provided by third party apps should work as well. Wagtail also provides a couple of field classes of its own: • RichTextField - For rich text content • StreamField - A block-based content field (see: Freeform page content using StreamField) For tagging, Wagtail fully supports django-taggit so we recommend using that.
Search
The search_fields attribute defines which fields are added to the search index and how they are indexed.
30 Chapter 1. Index Wagtail Documentation, Release 2.15a0
This should be a list of SearchField and FilterField objects. SearchField adds a field for full-text search. FilterField adds a field for filtering the results. A field can be indexed with both SearchField and FilterField at the same time (but only one instance of each). In the above example, we’ve indexed body for full-text search and date for filtering. The arguments that these field types accept are documented in indexing extra fields.
Editor panels
There are a few attributes for defining how the page’s fields will be arranged in the page editor interface: • content_panels - For content, such as main body text • promote_panels - For metadata, such as tags, thumbnail image and SEO title • settings_panels - For settings, such as publish date Each of these attributes is set to a list of EditHandler objects, which defines which fields appear on which tabs and how they are structured on each tab. Here’s a summary of the EditHandler classes that Wagtail provides out of the box. See Panel types for full descriptions. Basic These allow editing of model fields. The FieldPanel class will choose the correct widget based on the type of the field, though StreamField fields need to use a specialised panel class. • FieldPanel • StreamFieldPanel Structural These are used for structuring fields in the interface. • MultiFieldPanel • InlinePanel • FieldRowPanel Chooser ForeignKey fields to certain models can use one of the below ChooserPanel classes. These add a nice modal chooser interface, and the image/document choosers also allow uploading new files without leaving the page editor. • PageChooserPanel • ImageChooserPanel • DocumentChooserPanel • SnippetChooserPanel
Note: In order to use one of these choosers, the model being linked to must either be a page, image, document or snippet. Linking to any other model type is currently unsupported, you will need to use FieldPanel which will create a dropdown box.
The page editor can be customised further. See Customising the editing interface.
Parent page / subpage type rules
These two attributes allow you to control where page types may be used in your site. It allows you to define rules like “blog entries may only be created under a blog index”. Both take a list of model classes or model names. Model names are of the format app_label.ModelName. If the app_label is omitted, the same app is assumed. • parent_page_types limits which page types this type can be created under • subpage_types limits which page types can be created under this type By default, any page type can be created under any page type and it is not necessary to set these attributes if that’s the desired behaviour. Setting parent_page_types to an empty list is a good way of preventing a particular page type from being created in the editor interface.
Page URLs
The most common method of retrieving page URLs is by using the {% pageurl %} template tag. Since it’s called from a template, pageurl automatically includes the optimizations mentioned below. For more information, see pageurl. Page models also include several low-level methods for overriding or accessing page URLs.
Customising URL patterns for a page model
The Page.get_url_parts(request) method will not typically be called directly, but may be overridden to define custom URL routing for a given page model. It should return a tuple of (site_id, root_url, page_path), which are used by get_url and get_full_url (see below) to construct the given type of page URL. When overriding get_url_parts(), you should accept *args, **kwargs:
def get_url_parts(self, *args, **kwargs):
and pass those through at the point where you are calling get_url_parts on super (if applicable), e.g.:
super().get_url_parts(*args, **kwargs)
While you could pass only the request keyword argument, passing all arguments as-is ensures compatibility with any future changes to these method signatures. For more information, please see wagtail.core.models.Page.get_url_parts().
Obtaining URLs for page instances
The Page.get_url(request) method can be called whenever a page URL is needed. It defaults to returning local URLs (not including the protocol or domain) if it determines that the page is on the current site (via the hostname
32 Chapter 1. Index Wagtail Documentation, Release 2.15a0 in request); otherwise, a full URL including the protocol and domain is returned. Whenever possible, the optional request argument should be included to enable per-request caching of site-level URL information and facilitate the generation of local URLs. A common use case for get_url(request) is in any custom template tag your project may include for generating navigation menus. When writing such a custom template tag, ensure that it includes takes_context=True and use context.get('request') to safely pass the request or None if no request exists in the context. For more information, please see wagtail.core.models.Page.get_url(). In the event a full URL (including the protocol and domain) is needed, Page.get_full_url(request) can be used instead. Whenever possible, the optional request argument should be included to enable per-request caching of site-level URL information. For more information, please see wagtail.core.models.Page.get_full_url().
Template rendering
Each page model can be given an HTML template which is rendered when a user browses to a page on the site frontend. This is the simplest and most common way to get Wagtail content to end users (but not the only way).
Adding a template for a page model
Wagtail automatically chooses a name for the template based on the app label and model class name. Format: /.html For example, the template for the above blog page will be: blog/blog_page.html You just need to create a template in a location where it can be accessed with this name.
Template context
Wagtail renders templates with the page variable bound to the page instance being rendered. Use this to access the content of the page. For example, to get the title of the current page, use {{ page.title }}. All variables provided by context processors are also available.
Customising template context
All pages have a get_context method that is called whenever the template is rendered and returns a dictionary of variables to bind into the template. To add more variables to the template context, you can override this method: class BlogIndexPage(Page): ...
{% for entry in blog_entries %} {{ entry.title }} {% endfor %}
Changing the template
Set the template attribute on the class to use a different template file:
class BlogPage(Page): ...
template='other_template.html'
Dynamically choosing the template
The template can be changed on a per-instance basis by defining a get_template method on the page class. This method is called every time the page is rendered:
class BlogPage(Page): ...
use_other_template= models.BooleanField()
def get_template(self, request, *args, **kwargs): if self.use_other_template: return 'blog/other_blog_page.html'
return 'blog/blog_page.html'
In this example, pages that have the use_other_template boolean field set will use the blog/ other_blog_page.html template. All other pages will use the default blog/blog_page.html.
Ajax Templates
If you want to add AJAX functionality to a page, such as a paginated listing that updates in-place on the page rather than triggering a full page reload, you can set the ajax_template attribute to specify an alternative template to be used when the page is requested via an AJAX call (as indicated by the X-Requested-With: XMLHttpRequest HTTP header):
All page classes have a serve() method that internally calls the get_context and get_template methods and renders the template. This method is similar to a Django view function, taking a Django Request object and
34 Chapter 1. Index Wagtail Documentation, Release 2.15a0
returning a Django Response object. This method can also be overridden for complete control over page rendering. For example, here’s a way to make a page respond with a JSON representation of itself:
# Resizes the image to 300px width and gets a URL to it 'feed_image': self.feed_image.get_rendition('width-300').url, })
Inline models
Wagtail can nest the content of other models within the page. This is useful for creating repeated fields, such as related links or items to display in a carousel. Inline model content is also versioned with the rest of the page content. Each inline model requires the following: • It must inherit from wagtail.core.models.Orderable • It must have a ParentalKey to the parent model
Note: django-modelcluster and ParentalKey The model inlining feature is provided by django-modelcluster and the ParentalKey field type must be imported from there:
from modelcluster.fields import ParentalKey
ParentalKey is a subclass of Django’s ForeignKey, and takes the same arguments.
For example, the following inline model can be used to add related links (a list of name, url pairs) to the BlogPage model:
from django.db import models from modelcluster.fields import ParentalKey from wagtail.core.models import Orderable
class BlogPageRelatedLink(Orderable): page= ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='related_links
The first argument must match the value of the related_name attribute of the ParentalKey.
Working with pages
Wagtail uses Django’s multi-table inheritance feature to allow multiple page models to be used in the same tree. Each page is added to both Wagtail’s builtin Page model as well as its user-defined model (such as the BlogPage model created earlier). Pages can exist in Python code in two forms, an instance of Page or an instance of the page model. When working with multiple page types together, you will typically use instances of Wagtail’s Page model, which don’t give you access to any fields specific to their type.
# Get all pages in the database >>> from wagtail.core.models import Page >>> Page.objects.all() [,,,,
˓→Another Blog post>]
When working with a single page type, you can work with instances of the user-defined model. These give access to all the fields available in Page, along with any user-defined fields for that type.
# Get all blog entries in the database >>> BlogPage.objects.all() [,]
You can convert a Page object to its more specific user-defined equivalent using the .specific property. This may cause an additional database lookup.
>>> page= Page.objects.get(title="A Blog post") >>> page
# Note: the blog post is an instance of Page so we cannot access body, date or feed_
˓→image
>>> page.specific
Tips
36 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Friendly model names
You can make your model names more friendly to users of Wagtail by using Django’s internal Meta class with a verbose_name, e.g.: class HomePage(Page): ...
class Meta: verbose_name="homepage"
When users are given a choice of pages to create, the list of page types is generated by splitting your model names on each of their capital letters. Thus a HomePage model would be named “Home Page” which is a little clumsy. Defining verbose_name as in the example above would change this to read “Homepage”, which is slightly more conventional.
Page QuerySet ordering
Page-derived models cannot be given a default ordering by using the standard Django approach of adding an ordering attribute to the internal Meta class. class NewsItemPage(Page): publication_date= models.DateField() ...
class Meta: ordering=('-publication_date',) # will not work
This is because Page enforces ordering QuerySets by path. Instead, you must apply the ordering explicitly when constructing a QuerySet: news_items= NewsItemPage.objects.live().order_by('-publication_date')
Custom Page managers
You can add a custom Manager to your Page class. Any custom Managers should inherit from wagtail.core. models.PageManager: from django.db import models from wagtail.core.models import Page, PageManager class EventPageManager(PageManager): """ Custom manager for Event pages """ class EventPage(Page): start_date= models.DateField()
objects= EventPageManager()
Alternately, if you only need to add extra QuerySet methods, you can inherit from wagtail.core.models. PageQuerySet to build a custom Manager:
class EventPage(Page): start_date= models.DateField()
objects= EventPageManager()
1.2.2 Writing templates
Wagtail uses Django’s templating language. For developers new to Django, start with Django’s own template docu- mentation: Templates Python programmers new to Django/Wagtail may prefer more technical documentation: The Django template lan- guage: for Python programmers You should be familiar with Django templating basics before continuing with this documentation.
Templates
Every type of page or “content type” in Wagtail is defined as a “model” in a file called models.py. If your site has a blog, you might have a BlogPage model and another called BlogPageListing. The names of the models are up to the Django developer. For each page model in models.py, Wagtail assumes an HTML template file exists of (almost) the same name. The Front End developer may need to create these templates themselves by referring to models.py to infer template names from the models defined therein. To find a suitable template, Wagtail converts CamelCase names to snake_case. So for a BlogPage, a template blog_page.html will be expected. The name of the template file can be overridden per model if necessary. Template files are assumed to exist here:
For more information, see the Django documentation for the application directories template loader.
Page content
The data/content entered into each page is accessed/output through Django’s {{ double-brace }} notation. Each field from the model must be accessed by prefixing page.. e.g the page title {{ page.title }} or another field {{ page.author }}.
38 Chapter 1. Index Wagtail Documentation, Release 2.15a0
A custom variable name can be configured on the page model. If a custom name is defined, page is still available for use in shared templates. Additionally request. is available and contains Django’s request object.
Static assets
Static files e.g CSS, JS and images are typically stored here:
(The names “css”, “js” etc aren’t important, only their position within the tree.) Any file within the static folder should be inserted into your HTML using the {% static %} tag. More about it: Static files (tag).
User images
Images uploaded to a Wagtail site by its users (as opposed to a developer’s static files, mentioned above) go into the image library and from there are added to pages via the page editor interface. Unlike other CMSs, adding images to a page does not involve choosing a “version” of the image to use. Wagtail has no predefined image “formats” or “sizes”. Instead the template developer defines image manipulation to occur on the fly when the image is requested, via a special syntax within the template. Images from the library must be requested using this syntax, but a developer’s static images can be added via conven- tional means e.g img tags. Only images from the library can be manipulated on the fly. Read more about the image manipulation syntax here How to use images in templates.
Template tags & filters
In addition to Django’s standard tags and filters, Wagtail provides some of its own, which can be load-ed just like any other.
Images (tag)
The image tag inserts an XHTML-compatible img element into the page, setting its src, width, height and alt. See also More control over the img tag. The syntax for the image tag is thus:
See How to use images in templates for full documentation.
Rich text (filter)
This filter takes a chunk of HTML content and renders it as safe HTML in the page. Importantly, it also expands internal shorthand references to embedded images, and links made in the Wagtail editor, into fully-baked HTML ready for display. Only fields using RichTextField need this applied in the template.
As Wagtail does not impose any styling of its own on templates, images and embedded media will be displayed at a fixed width as determined by the HTML. Images can be made to resize to fit their container using a CSS rule such as the following:
.body img { max-width: 100%; height: auto; }
where body is a container element in your template surrounding the images. Making embedded media resizable is also possible, but typically requires custom style rules matching the media’s aspect ratio. To assist in this, Wagtail provides built-in support for responsive embeds, which can be enabled by setting WAGTAILEMBEDS_RESPONSIVE_HTML = True in your project settings. This adds a CSS class of responsive-object and an inline padding-bottom style to the embed, to be used in conjunction with the following CSS:
40 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Internal links (tag)
pageurl
Takes a Page object and returns a relative URL (/foo/bar/) if within the same Site as the current page, or absolute (http://example.com/foo/bar/) if not.
A fallback keyword argument can be provided - this can be a URL string, a named URL route that can be resolved with no parameters, or an object with a get_absolute_url method, and will be used as a substitute URL when the passed page is None.
{% load wagtailcore_tags %}
{% for publication in page.related_publications.all %}
Takes any slug as defined in a page’s “Promote” tab and returns the URL for the matching Page. If multiple pages exist with the same slug, the page chosen is undetermined. Like pageurl, this will try to provide a relative link if possible, but will default to an absolute link if the Page is on a different Site. This is most useful when creating shared page furniture, e.g. top level navigation or site-wide links.
Used to load anything from your static files directory. Use of this tag avoids rewriting all static paths if hosting arrangements change, as they might between development and live environments.
{% load static %} ...
Notice that the full path name is not required and the path snippet you enter only need begin with the parent app’s directory name.
Returns the Site object corresponding to the current request.
{% load wagtailcore_tags %}
{% wagtail_site as current_site %}
Wagtail User Bar
This tag provides a contextual flyout menu for logged-in users. The menu gives editors the ability to edit the current page or add a child page, besides the options to show the page in the Wagtail page explorer or jump to the Wagtail admin dashboard. Moderators are also given the ability to accept or reject a page being previewed as part of content moderation. This tag may be used on standard Django views, without page object. The user bar will contain one item pointing to the admin. We recommend putting the tag near the top of the
element so keyboard users can reach it. You should consider putting the tag after any skip links but before the navigation and main content of your page.
{% load wagtailuserbar %} ...
Skip to content {% wagtailuserbar %} {# This is a good place for the userbar #} ...
By default the User Bar appears in the bottom right of the browser window, inset from the edge. If this conflicts with your design it can be moved by passing a parameter to the template tag. These examples show you how to position the userbar in each corner of the screen:
The userbar can be positioned where it works best with your design. Alternatively, you can position it with a CSS rule in your own CSS files, for example:
42 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Varying output between preview and live
Sometimes you may wish to vary the template output depending on whether the page is being previewed or viewed live. For example, if you have visitor tracking code such as Google Analytics in place on your site, it’s a good idea to leave this out when previewing, so that editor activity doesn’t appear in your analytics reports. Wagtail provides a request.is_preview variable to distinguish between preview and live:
{% if not request.is_preview %} {% endif %}
1.2.3 How to use images in templates
The image tag inserts an XHTML-compatible img element into the page, setting its src, width, height and alt. See also More control over the img tag. The syntax for the tag is thus:
{% image [image][resize-rule] %}
Both the image and resize rule must be passed to the template tag. For example:
{% load wagtailimages_tags %} ...
{% image page.photo width-400 %}
{% image page.photo fill-80x80 %}
In the above syntax example [image] is the Django object referring to the image. If your page model defined a field called “photo” then [image] would probably be page.photo. The [resize-rule] defines how the image is to be resized when inserted into the page. Various resizing methods are supported, to cater to different use cases (e.g. lead images that span the whole width of the page, or thumbnails to be cropped to a fixed size). Note that a space separates [image] and [resize-rule], but the resize rule must not contain spaces. The width is always specified before the height. Resized images will maintain their original aspect ratio unless the fill rule is used, which may result in some pixels being cropped. The available resizing methods are as follows: max (takes two dimensions)
{% image page.photo max-1000x500 %}
Fit within the given dimensions. The longest edge will be reduced to the matching dimension specified. For example, a portrait image of width 1000 and height 2000, treated with the max-1000x500 rule (a landscape layout) would result in the image being shrunk so the height was 500 pixels and the width was 250. min (takes two dimensions)
Fig. 1: Example: The image will keep its proportions but fit within the max (green line) dimensions provided.
{% image page.photo min-500x200 %}
Cover the given dimensions. This may result in an image slightly larger than the dimensions you specify. A square image of width 2000 and height 2000, treated with the min-500x200 rule would have its height and width changed to 500, i.e matching the width of the resize-rule, but greater than the height. width (takes one dimension)
{% image page.photo width-640 %}
Reduces the width of the image to the dimension specified. height (takes one dimension)
{% image page.photo height-480 %}
Reduces the height of the image to the dimension specified. scale (takes percentage)
{% image page.photo scale-50 %}
Resize the image to the percentage specified. fill (takes two dimensions and an optional -c parameter)
{% image page.photo fill-200x200 %}
Resize and crop to fill the exact dimensions specified.
44 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Fig. 2: Example: The image will keep its proportions while filling at least the min (green line) dimensions provided.
This can be particularly useful for websites requiring square thumbnails of arbitrary images. For example, a landscape image of width 2000 and height 1000 treated with the fill-200x200 rule would have its height reduced to 200, then its width (ordinarily 400) cropped to 200. This resize-rule will crop to the image’s focal point if it has been set. If not, it will crop to the centre of the image. On images that won’t upscale It’s possible to request an image with fill dimensions that the image can’t support without upscaling. e.g. an image of width 400 and height 200 requested with fill-400x400. In this situation the ratio of the requested fill will be matched, but the dimension will not. So that example 400x200 image (a 2:1 ratio) could become 200x200 (a 1:1 ratio, matching the resize-rule). Cropping closer to the focal point By default, Wagtail will only crop enough to change the aspect ratio of the image to match the ratio in the resize-rule. In some cases (e.g. thumbnails), it may be preferable to crop closer to the focal point, so that the subject of the image is more prominent. You can do this by appending -c at the end of the resize-rule. For example, if you would like the image to be cropped as closely as possible to its focal point, add -c100:
{% image page.photo fill-200x200-c100 %}
This will crop the image as much as it can, without cropping into the focal point. If you find that -c100 is too close, you can try -c75 or -c50. Any whole number from 0 to 100 is accepted. original (takes no dimensions)
Fig. 3: Example: The image is scaled and also cropped (red line) to fit as much of the image as possible within the provided dimensions.
Fig. 4: Example: The focal point is set off centre so the image is scaled and also cropped like fill, however the center point of the crop is positioned closer the focal point.
46 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Fig. 5: Example: With -c75 set, the final crop will be closer to the focal point.
{% image page.photo original %}
Renders the image at its original size.
Note: Wagtail does not allow deforming or stretching images. Image dimension ratios will always be kept. Wag- tail also does not support upscaling. Small images forced to appear at larger sizes will “max out” at their native dimensions.
More control over the img tag
Wagtail provides two shortcuts to give greater control over the img element: 1. Adding attributes to the {% image %} tag Extra attributes can be specified with the syntax attribute="value":
You can set a more relevant alt attribute this way, overriding the one automatically generated from the title of the image. The src, width, and height attributes can also be overridden, if necessary. 2. Generating the image “as foo” to access individual properties Wagtail can assign the image data to another variable using Django’s as syntax:
Note: The image property used for the src attribute is image.url, not image.src.
This syntax exposes the underlying image Rendition (tmp_photo) to the developer. A “Rendition” contains the information specific to the way you’ve requested to format the image using the resize-rule, i.e. dimensions and source URL. The following properties are available: url URL to the resized version of the image. This may be a local URL (such as /static/images/example. jpg) or a full URL (such as https://assets.example.com/images/example.jpg), depending on how static files are configured. width Image width after resizing. height Image height after resizing. alt Alternative text for the image, typically taken from the image title. attrs A shorthand for outputting the attributes src, width, height and alt in one go:
full_url Same as url, but always returns a full absolute URL. This requires BASE_URL to be set in the project settings. This is useful for images that will be re-used outside of the current site, such as social share images:
If your site defines a custom image model using AbstractImage, any additional fields you add to an image (e.g. a copyright holder) are not included in the rendition. Therefore, if you’d added the field author to your AbstractImage in the above example, you’d access it using {{ page.photo.author }} rather than {{ tmp_photo.author }}. (Due to the links in the database between renditions and their parent image, you could access it as {{ tmp_photo. image.author }}, but that has reduced readability.)
The attrs shortcut
You can also use the attrs property as a shorthand to output the attributes src, width, height and alt in one go:
48 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Alternative HTML tags
The as keyword allows alternative HTML image tags (such as or ) to be used. For example, to use the tag:
And to use the tag (based on the Mountains example from the AMP docs):
{% image image width-550 format-webp as webp_image %} {% image image width-550 format-jpeg as jpeg_image %}
Images embedded in rich text
The information above relates to images defined via image-specific fields in your model. However, images can also be embedded arbitrarily in Rich Text fields by the page editor (see Rich Text (HTML)). Images embedded in Rich Text fields can’t be controlled by the template developer as easily. There are no image objects to work with, so the {% image %} template tag can’t be used. Instead, editors can choose from one of a number of image “Formats” at the point of inserting images into their text. Wagtail comes with three pre-defined image formats, but more can be defined in Python by the developer. These formats are: Full width Creates an image rendition using width-800, giving the tag the CSS class full-width. Left-aligned Creates an image rendition using width-500, giving the tag the CSS class left. Right-aligned Creates an image rendition using width-500, giving the tag the CSS class right.
Note: The CSS classes added to images do not come with any accompanying stylesheets, or inline styles. e.g. the left class will do nothing, by default. The developer is expected to add these classes to their front end CSS files, to define exactly what they want left, right or full-width to mean.
For more information about image formats, including creating your own, see Image Formats in the Rich Text Editor
Output image format
Wagtail may automatically change the format of some images when they are resized: • PNG and JPEG images don’t change format
• GIF images without animation are converted to PNGs • BMP images are converted to PNGs • WebP images are converted to PNGs It is also possible to override the output format on a per-tag basis by using the format filter after the resize rule. For example, to make the tag always convert the image to a JPEG, use format-jpeg:
{% image page.photo width-400 format-jpeg %}
You may also use format-png or format-gif.
Lossless WebP
You can encode the image into lossless WebP format by using the format-webp-lossless filter:
The PNG and GIF image formats both support transparency, but if you want to convert images to JPEG format, the transparency will need to be replaced with a solid background color. By default, Wagtail will set the background to white. But if a white background doesn’t fit your design, you can specify a color using the bgcolor filter. This filter takes a single argument, which is a CSS 3 or 6 digit hex code representing the color you would like to use:
{# Sets the image background to black #} {% image page.photo width-400 bgcolor-000 format-jpeg %}
Image quality
Wagtail’s JPEG and WebP image quality settings default to 85 (which is quite high). This can be changed either globally or on a per-tag basis.
Changing globally
Use the WAGTAILIMAGES_JPEG_QUALITY and WAGTAILIMAGES_WEBP_QUALITY settings to change the global defaults of JPEG and WebP quality:
# settings.py
# Make low-quality but small images WAGTAILIMAGES_JPEG_QUALITY= 40 WAGTAILIMAGES_WEBP_QUALITY= 45
Note that this won’t affect any previously generated images so you may want to delete all renditions so they can regenerate with the new setting. This can be done from the Django shell:
50 Chapter 1. Index Wagtail Documentation, Release 2.15a0
# Replace this with your custom rendition model if you use one >>> from wagtail.images.models import Rendition >>> Rendition.objects.all().delete()
Changing per-tag
It’s also possible to have different JPEG and WebP qualities on individual tags by using jpegquality and webpquality filters. This will always override the default setting:
Note that this will have no effect on PNG or GIF files. If you want all images to be low quality, you can use this filter with format-jpeg or format-webp (which forces all images to output in JPEG or WebP format):
All of the image transformations mentioned above can also be used directly in Python code. See Generating renditions in Python.
1.2.4 Search
Wagtail provides a comprehensive and extensible search interface. In addition, it provides ways to promote search results through “Editor’s Picks”. Wagtail also collects simple statistics on queries made through the search interface.
Indexing
To make a model searchable, you’ll need to add it into the search index. All pages, images and documents are indexed for you, so you can start searching them right away. If you have created some extra fields in a subclass of Page or Image, you may want to add these new fields to the search index too so that a user’s search query will match on their content. See Indexing extra fields for info on how to do this. If you have a custom model that you would like to make searchable, see Indexing custom models.
Updating the index
If the search index is kept separate from the database (when using Elasticsearch for example), you need to keep them both in sync. There are two ways to do this: using the search signal handlers, or calling the update_index command periodically. For best speed and reliability, it’s best to use both if possible.
wagtailsearch provides some signal handlers which bind to the save/delete signals of all indexed models. This would automatically add and delete them from all backends you have registered in WAGTAILSEARCH_BACKENDS. These signal handlers are automatically registered when the wagtail.search app is loaded. In some cases, you may not want your content to be automatically reindexed and instead rely on the update_index command for indexing. If you need to disable these signal handlers, use one of the following methods:
Disabling auto update signal handlers for a model
You can disable the signal handlers for an individual model by adding search_auto_update = False as an attribute on the model class.
Disabling auto update signal handlers for a search backend/whole site
You can disable the signal handlers for a whole search backend by setting the AUTO_UPDATE setting on the backend to False. If all search backends have AUTO_UPDATE set to False, the signal handlers will be completely disabled for the whole site. For documentation on the AUTO_UPDATE setting, see AUTO_UPDATE.
The update_index command
Wagtail also provides a command for rebuilding the index from scratch. ./manage.py update_index It is recommended to run this command once a week and at the following times: • whenever any pages have been created through a script (after an import, for example) • whenever any changes have been made to models or search configuration The search may not return any results while this command is running, so avoid running it at peak times.
Note: The update_index command is also aliased as wagtail_update_index, for use when another in- stalled package (such as Haystack) provides a conflicting update_index command. In this case, the other pack- age’s entry in INSTALLED_APPS should appear above wagtail.search so that its update_index command takes precedence over Wagtail’s.
Indexing extra fields
Warning: Indexing extra fields is only supported by the Elasticsearch Backend and PostgreSQL Backend. In- dexing extra fields is not supported by the Database Backend (default). If you’re using the database backend, any other fields you define via search_fields will be ignored.
52 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Fields must be explicitly added to the search_fields property of your Page-derived model, in order for you to be able to search/filter on them. This is done by overriding search_fields to append a list of extra SearchField/FilterField objects to it.
Example
This creates an EventPage model with two fields: description and date. description is indexed as a SearchField and date is indexed as a FilterField
from wagtail.search import index from django.utils import timezone
class EventPage(Page): description= models.TextField() date= models.DateField()
search_fields= Page.search_fields+[ # Inherit search_fields from Page index.SearchField('description'), index.FilterField('date'), ]
# Get future events which contain the string "Christmas" in the title or description >>> EventPage.objects.filter(date__gt=timezone.now()).search("Christmas")
index.SearchField
These are used for performing full-text searches on your models, usually for text fields.
Options
• partial_match (boolean) - Setting this to true allows results to be matched on parts of words. For example, this is set on the title field by default, so a page titled Hello World! will be found if the user only types Hel into the search box. • boost (int/float) - This allows you to set fields as being more important than others. Setting this to a high number on a field will cause pages with matches in that field to be ranked higher. By default, this is set to 2 on the Page title field and 1 on all other fields. • es_extra (dict) - This field is to allow the developer to set or override any setting on the field in the Elastic- search mapping. Use this if you want to make use of any Elasticsearch features that are not yet supported in Wagtail.
index.FilterField
These are added to the search index but are not used for full-text searches. Instead, they allow you to run filters on your search results.
This allows you to index fields from related objects. It works on all types of related fields, including their reverse accessors. For example, if we have a book that has a ForeignKey to its author, we can nest the author’s name and date_of_birth fields inside the book: from wagtail.search import index class Book(models.Model, index.Indexed): ...
This will allow you to search for books by their author’s name. It works the other way around as well. You can index an author’s books, allowing an author to be searched for by the titles of books they’ve published: from wagtail.search import index class Author(models.Model, index.Indexed): ...
It’s not possible to filter on any index.FilterFields within index.RelatedFields using the QuerySet API. However, the fields are indexed, so it should be possible to use them by querying Elasticsearch manually. Filtering on index.RelatedFields with the QuerySet API is planned for a future release of Wagtail.
Indexing callables and other attributes
54 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Note: This is not supported in the Database Backend (default)
Search/filter fields do not need to be Django model fields. They can also be any method or attribute on your model class. One use for this is indexing the get_*_display methods Django creates automatically for fields with choices. from wagtail.search import index class EventPage(Page): IS_PRIVATE_CHOICES=( (False,"Public"), (True,"Private"), )
search_fields= Page.search_fields+[ # Index the human-readable string for searching. index.SearchField('get_is_private_display'),
# Index the boolean value for filtering. index.FilterField('is_private'), ]
Callables also provide a way to index fields from related models. In the example from Inline Panels and Model Clusters, to index each BookPage by the titles of its related_links: class BookPage(Page): # ... def get_related_link_titles(self): # Get list of titles and concatenate them return '\n'.join(self.related_links.all().values_list('name', flat=True))
Any Django model can be indexed and searched. To do this, inherit from index.Indexed and add some search_fields to the model. from wagtail.search import index class Book(index.Indexed, models.Model): title= models.CharField(max_length=255) genre= models.CharField(max_length=255, choices=GENRE_CHOICES) author= models.ForeignKey(Author, on_delete=models.CASCADE) published_date= models.DateTimeField()
search_fields=[ index.SearchField('title', partial_match=True, boost=10), (continues on next page)
# As this model doesn't have a search method in its QuerySet, we have to call search
˓→directly on the backend >>> from wagtail.search.backends import get_search_backend >>>s= get_search_backend()
# Run a search for a book by Roald Dahl >>> roald_dahl= Author.objects.get(name="Roald Dahl") >>>s.search("chocolate factory", Book.objects.filter(author=roald_dahl)) []
Searching
Searching QuerySets
Wagtail search is built on Django’s QuerySet API. You should be able to search any Django QuerySet provided the model and the fields being filtered on have been added to the search index.
Searching Pages
Wagtail provides a shortcut for searching pages: the .search() QuerySet method. You can call this on any PageQuerySet. For example:
All other methods of PageQuerySet can be used with search(). For example:
# Search all live EventPages that are under the events index >>> EventPage.objects.live().descendant_of(events_index).search("Event") [,]
Note: The search() method will convert your QuerySet into an instance of one of Wagtail’s SearchResults classes (depending on backend). This means that you must perform filtering before calling search().
Searching Images, Documents and custom models
Wagtail’s document and image models provide a search method on their QuerySets, just as pages do:
By default, Wagtail will search all fields that have been indexed using index.SearchField. This can be limited to a certain set of fields by using the fields keyword argument:
# Search just the title field >>> EventPage.objects.search("Event", fields=["title"]) [,]
Faceted search
Wagtail supports faceted search which is a kind of filtering based on a taxonomy field (such as category or page type). The .facet(field_name) method returns an OrderedDict. The keys are the IDs of the related objects that have been referenced by the specified field, and the values are the number of references found for each ID. The results are ordered by number of references descending. For example, to find the most common page types in the search results:
# Note: The keys correspond to the ID of a ContentType object; the values are the # number of pages returned for that type OrderedDict([ ('2', 4), # 4 pages have content_type_id == 2 ('1', 2), # 2 pages have content_type_id == 1 ])
The search operator specifies how search should behave when the user has typed in multiple search terms. There are two possible values: • “or” - The results must match at least one term (default for Elasticsearch) • “and” - The results must match all terms (default for database search) Both operators have benefits and drawbacks. The “or” operator will return many more results but will likely contain a lot of results that aren’t relevant. The “and” operator only returns results that contain all search terms, but require the user to be more precise with their query. We recommend using the “or” operator when ordering by relevance and the “and” operator when ordering by anything else (note: the database backend doesn’t currently support ordering by relevance). Here’s an example of using the operator keyword argument:
# The database contains a "Thing" model with the following items: # - Hello world # - Hello # - World
# Search with the "or" operator >>>s= get_search_backend() >>>s.search("Hello world", Things, operator="or")
# All records returned as they all contain either "hello" or "world" [,,]
# Search with the "and" operator >>>s= get_search_backend() >>>s.search("Hello world", Things, operator="and")
# Only "hello world" returned as that's the only item that contains both terms []
For page, image and document models, the operator keyword argument is also supported on the QuerySet’s search method:
# All pages containing either "hello" or "world" are returned [, , ]
Phrase searching
Phrase searching is used for finding whole sentence or phrase rather than individual terms. The terms must appear together and in the same order. For example:
>>> from wagtail.search.query import Phrase
>>> Page.objects.search(Phrase("Hello world")) (continues on next page)
58 Chapter 1. Index Wagtail Documentation, Release 2.15a0
(continued from previous page) []
>>> Page.objects.search(Phrase("World hello")) []
If you are looking to implement phrase queries using the double-quote syntax, see Query string parsing.
Complex search queries
Through the use of search query classes, Wagtail also supports building search queries as Python objects which can be wrapped by and combined with other search queries. The following classes are available: PlainText(query_string, operator=None, boost=1.0) This class wraps a string of separate terms. This is the same as searching without query classes. It takes a query string, operator and boost. For example:
>>> from wagtail.search.query import PlainText >>> Page.objects.search(PlainText("Hello world"))
# Multiple plain text queries can be combined. This example will match both "hello
˓→world" and "Hello earth" >>> Page.objects.search(PlainText("Hello")& (PlainText("world")| PlainText("earth
˓→")))
Phrase(query_string) This class wraps a string containing a phrase. See previous section for how this works. For example:
# This example will match both the phrases "hello world" and "Hello earth" >>> Page.objects.search(Phrase("Hello world")| Phrase("Hello earth"))
Boost(query, boost) This class boosts the score of another query. For example:
>>> from wagtail.search.query import PlainText, Boost
# This example will match both the phrases "hello world" and "Hello earth" but
˓→matches for "hello world" will be ranked higher >>> Page.objects.search(Boost(Phrase("Hello world"), 10.0)| Phrase("Hello earth"))
Note that this isn’t supported by the PostgreSQL or database search backends.
Query string parsing
The previous sections show how to construct a phrase search query manually, but a lot of search engines (Wagtail admin included, try it!) support writing phrase queries by wrapping the phrase with double-quotes. In addition to phrases, you might also want to allow users to add filters into the query using the colon syntax (hello world published:yes).
These two features can be implemented using the parse_query_string utility function. This function takes a query string that a user typed and returns a query object and dictionary of filters: For example:
>>> from wagtail.search.utils import parse_query_string >>> filters, query= parse_query_string('my query string"this is a phrase" this-is-
˓→a:filter', operator='and')
>>> filters { 'this-is-a': 'filter', }
>>> query And([ PlainText("my query string", operator='and'), Phrase("this is a phrase"), ])
Here’s an example of how this function can be used in a search view: from wagtail.search.utils import parse_query_string def search(request): query_string= request.GET['query']
# Published filter # An example filter that accepts either `published:yes` or `published:no` and
˓→filters the pages accordingly published_filter= filters.get('published') published_filter= published_filter and published_filter.lower() if published_filter in ['yes','true']: pages= pages.filter(live= True) elif published_filter in ['no','false']: pages= pages.filter(live= False)
By default, search results are ordered by relevance, if the backend supports it. To preserve the QuerySet’s existing ordering, the order_by_relevance keyword argument needs to be set to False on the search() method. For example:
# Get a list of events ordered by date >>> EventPage.objects.order_by('date').search("Event", order_by_relevance=False)
# Events ordered by date [,,]
60 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Annotating results with score
For each matched result, Elasticsearch calculates a “score”, which is a number that represents how relevant the result is based on the user’s query. The results are usually ordered based on the score. There are some cases where having access to the score is useful (such as programmatically combining two queries for different models). You can add the score to each result by calling the .annotate_score(field) method on the SearchQuerySet. For example:
>>> events= EventPage.objects.search("Event").annotate_score("_score") >>> for event in events: ... print(event.title, event._score) ... ("Easter", 2.5), ("Halloween", 1.7), ("Christmas", 1.5),
Note that the score itself is arbitrary and it is only useful for comparison of results for the same query.
An example page search view
Here’s an example Django view that could be used to add a “search” page to your site:
# views.py from django.shortcuts import render from wagtail.core.models import Page from wagtail.search.models import Query def search(request): # Search search_query= request.GET.get('query', None) if search_query: search_results= Page.objects.live().search(search_query)
# Log the query so Wagtail can suggest promoted results Query.get(search_query).add_hit() else: search_results= Page.objects.none()
{% if result.search_description %} {{ result.search_description|safe }} {% endif %}
{% endfor %}
{% elif search_query %} No results found {% else %} Please type something into the search box {% endif %} {% endblock %}
Promoted search results
“Promoted search results” allow editors to explicitly link relevant content to search terms, so results pages can contain curated content in addition to results from the search engine. This functionality is provided by the search_promotions contrib module.
Backends
Wagtailsearch has support for multiple backends, giving you the choice between using the database for search or an external service such as Elasticsearch. The database backend is enabled by default. You can configure which backend to use with the WAGTAILSEARCH_BACKENDS setting:
By default, Wagtail will automatically keep all indexes up to date. This could impact performance when editing content, especially if your index is hosted on an external service. The AUTO_UPDATE setting allows you to disable this on a per-index basis:
62 Chapter 1. Index Wagtail Documentation, Release 2.15a0
If you have disabled auto update, you must run the update_index command on a regular basis to keep the index in sync with the database.
ATOMIC_REBUILD
Warning: This option may not work on Elasticsearch version 5.4.x, due to a bug in the handling of aliases- please upgrade to 5.5 or later.
By default (when using the Elasticsearch backend), when the update_index command is run, Wagtail deletes the index and rebuilds it from scratch. This causes the search engine to not return results until the rebuild is complete and is also risky as you can’t rollback if an error occurs. Setting the ATOMIC_REBUILD setting to True makes Wagtail rebuild into a separate index while keep the old index active until the new one is fully built. When the rebuild is finished, the indexes are swapped atomically and the old index is deleted.
BACKEND
Here’s a list of backends that Wagtail supports out of the box.
Database Backend (default)
wagtail.search.backends.db The database backend is very basic and is intended only to be used in development and on small sites. It cannot order results by relevance, severely hampering its usefulness when searching a large collection of pages. It also doesn’t support: • Searching on fields in subclasses of Page (unless the class is being searched directly) • Indexing callables and other attributes • Converting accented characters to ASCII If any of these features are important to you, we recommend using Elasticsearch instead.
PostgreSQL Backend
wagtail.contrib.postgres_search.backend If you use PostgreSQL for your database and your site has less than a million pages, you probably want to use this backend. See PostgreSQL search engine for more detail.
Elasticsearch versions 5, 6 and 7 are supported. Use the appropriate backend for your version: wagtail.search.backends.elasticsearch5 (Elasticsearch 5.x) wagtail.search.backends.elasticsearch6 (Elasticsearch 6.x) wagtail.search.backends.elasticsearch7 (Elasticsearch 7.x) Prerequisites are the Elasticsearch service itself and, via pip, the elasticsearch-py package. The major version of the package must match the installed version of Elasticsearch:
pip install "elasticsearch>=5.0.0,<6.0.0" # for Elasticsearch 5.x
pip install "elasticsearch>=6.4.0,<7.0.0" # for Elasticsearch 6.x
pip install "elasticsearch>=7.0.0,<8.0.0" # for Elasticsearch 7.x
Warning: Version 6.3.1 of the Elasticsearch client library is incompatible with Wagtail. Use 6.4.0 or above.
Other than BACKEND, the keys are optional and default to the values shown. Any defined key in OPTIONS is passed directly to the Elasticsearch constructor as case-sensitive keyword argument (e.g. 'max_retries': 1). A username and password may be optionally be supplied to the URL field to provide authentication credentials for the Elasticsearch service:
INDEX_SETTINGS is a dictionary used to override the default settings to create the index. The default settings are defined inside the ElasticsearchSearchBackend class in the module wagtail/wagtail/search/ backends/elasticsearch7.py. Any new key is added, any existing key, if not a dictionary, is replaced with the new value. Here’s a sample on how to configure the number of shards and setting the Italian LanguageAnalyzer as the default analyzer:
64 Chapter 1. Index Wagtail Documentation, Release 2.15a0
If you prefer not to run an Elasticsearch server in development or production, there are many hosted services available, including Bonsai, who offer a free account suitable for testing and development. To use Bonsai: • Sign up for an account at Bonsai • Use your Bonsai dashboard to create a Cluster. • Configure URLS in the Elasticsearch entry in WAGTAILSEARCH_BACKENDS using the Cluster URL from your Bonsai dashboard • Run ./manage.py update_index
Amazon AWS Elasticsearch
The Elasticsearch backend is compatible with Amazon Elasticsearch Service, but requires additional configuration to handle IAM based authentication. This can be done with the requests-aws4auth package along with the following configuration: from elasticsearch import RequestsHttpConnection from requests_aws4auth import AWS4Auth
Wagtail search backends implement the interface defined in wagtail/wagtail/wagtailsearch/ backends/base.py. At a minimum, the backend’s search() method must return a collection of objects or model.objects.none(). For a fully-featured search backend, examine the Elasticsearch backend code in elasticsearch.py.
Indexing
To make objects searchable, they must first be added to the search index. This involves configuring the models and fields that you would like to index (which is done for you for Pages, Images and Documents), and then actually inserting them into the index. See Updating the index for information on how to keep the objects in your search index in sync with the objects in your database. If you have created some extra fields in a subclass of Page or Image, you may want to add these new fields to the search index, so a user’s search query can match the Page or Image’s extra content. See Indexing extra fields. If you have a custom model which doesn’t derive from Page or Image that you would like to make searchable, see Indexing custom models.
Searching
Wagtail provides an API for performing search queries on your models. You can also perform search queries on Django QuerySets. See Searching.
Backends
Wagtail provides three backends for storing the search index and performing search queries: Elasticsearch, the database, and PostgreSQL (Django >=1.10 required). It’s also possible to roll your own search backend. See Backends
1.2.5 Snippets
Snippets are pieces of content which do not necessitate a full webpage to render. They could be used for making secondary content, such as headers, footers, and sidebars, editable in the Wagtail admin. Snippets are Django models which do not inherit the Page class and are thus not organized into the Wagtail tree. However, they can still be made editable by assigning panels and identifying the model as a snippet with the register_snippet class decorator. Snippets lack many of the features of pages, such as being orderable in the Wagtail admin or having a defined URL. Decide carefully if the content type you would want to build into a snippet might be more suited to a page.
Snippet Models
Here’s an example snippet model:
66 Chapter 1. Index Wagtail Documentation, Release 2.15a0
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel from wagtail.snippets.models import register_snippet
...
@register_snippet class Advert(models.Model): url= models.URLField(null= True, blank=True) text= models.CharField(max_length=255)
panels=[ FieldPanel('url'), FieldPanel('text'), ]
def __str__(self): return self.text
The Advert model uses the basic Django model class and defines two properties: text and URL. The editing interface is very close to that provided for Page-derived models, with fields assigned in the panels property. Snippets do not use multiple tabs of fields, nor do they provide the “save as draft” or “submit for moderation” features. @register_snippet tells Wagtail to treat the model as a snippet. The panels list defines the fields to show on the snippet editing page. It’s also important to provide a string representation of the class through def __str__(self): so that the snippet objects make sense when listed in the Wagtail admin.
Including Snippets in Template Tags
The simplest way to make your snippets available to templates is with a template tag. This is mostly done with vanilla Django, so perhaps reviewing Django’s documentation for django custom template tags will be more helpful. We’ll go over the basics, though, and point out any considerations to make for Wagtail. First, add a new python file to a templatetags folder within your app - for example, myproject/demo/ templatetags/demo_tags.py. We’ll need to load some Django modules and our app’s models, and ready the register decorator:
from django import template from demo.models import Advert register= template.Library()
@register.inclusion_tag() takes two variables: a template and a boolean on whether that template should be passed a request context. It’s a good idea to include request contexts in your custom template tags, since some Wagtail-specific template tags like pageurl need the context to work properly. The template tag function could take
arguments and filter the adverts to return a specific instance of the model, but for brevity we’ll just use Advert. objects.all(). Here’s what’s in the template used by this template tag:
Then, in your own page templates, you can include your snippet template tag with:
{% load wagtailcore_tags demo_tags %}
...
{% block content %}
...
{% adverts %}
{% endblock %}
Binding Pages to Snippets
In the above example, the list of adverts is a fixed list that is displayed via the custom template tag independent of any other content on the page. This might be what you want for a common panel in a sidebar, but, in another scenario, you might wish to display just one specific instance of a snippet on a particular page. This can be accomplished by defining a foreign key to the snippet model within your page model and adding a SnippetChooserPanel to the page’s content_panels list. For example, if you wanted to display a specific advert on a BookPage instance:
from wagtail.snippets.edit_handlers import SnippetChooserPanel # ... class BookPage(Page): advert= models.ForeignKey( 'demo.Advert', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' )
The snippet could then be accessed within your template as page.advert. To attach multiple adverts to a page, the SnippetChooserPanel can be placed on an inline child object of BookPage rather than on BookPage itself. Here, this child model is named BookPageAdvertPlacement (so called because there is one such object for each time that an advert is placed on a BookPage):
68 Chapter 1. Index Wagtail Documentation, Release 2.15a0
from django.db import models from wagtail.core.models import Page, Orderable from wagtail.snippets.edit_handlers import SnippetChooserPanel from modelcluster.fields import ParentalKey
... class BookPageAdvertPlacement(Orderable, models.Model): page= ParentalKey('demo.BookPage', on_delete=models.CASCADE, related_name=
These child objects are now accessible through the page’s advert_placements property, and from there we can access the linked Advert snippet as advert. In the template for BookPage, we could include the following:
{% for advert_placement in page.advert_placements.all %}
If a snippet model inherits from wagtail.search.index.Indexed, as described in Indexing custom models, Wagtail will automatically add a search box to the chooser interface for that snippet type. For example, the Advert snippet could be made searchable as follows:
Adding tags to snippets is very similar to adding tags to pages. The only difference is that taggit.manager. TaggableManager should be used in the place of ClusterTaggableManager. from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from taggit.models import TaggedItemBase from taggit.managers import TaggableManager class AdvertTag(TaggedItemBase): content_object= ParentalKey('demo.Advert', on_delete=models.CASCADE, related_
˓→name='tagged_items')
@register_snippet class Advert(ClusterableModel): ... tags= TaggableManager(through=AdvertTag, blank= True)
panels=[ ... FieldPanel('tags'), ]
The documentation on tagging pages has more information on how to use tags in views.
1.2.6 How to use StreamField for mixed content
StreamField provides a content editing model suitable for pages that do not follow a fixed structure – such as blog posts or news stories – where the text may be interspersed with subheadings, images, pull quotes and video. It’s also suitable for more specialised content types, such as maps and charts (or, for a programming blog, code snippets). In this model, these different content types are represented as a sequence of ‘blocks’, which can be repeated and arranged in any order. For further background on StreamField, and why you would use it instead of a rich text field for the article body, see the blog post Rich text fields and faster horses. StreamField also offers a rich API to define your own block types, ranging from simple collections of sub-blocks (such as a ‘person’ block consisting of first name, surname and photograph) to completely custom components with
70 Chapter 1. Index Wagtail Documentation, Release 2.15a0
their own editing interface. Within the database, the StreamField content is stored as JSON, ensuring that the full informational content of the field is preserved, rather than just an HTML representation of it.
Using StreamField
StreamField is a model field that can be defined within your page model like any other field:
from django.db import models
from wagtail.core.models import Page from wagtail.core.fields import StreamField from wagtail.core import blocks from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel from wagtail.images.blocks import ImageChooserBlock class BlogPage(Page): author= models.CharField(max_length=255) date= models.DateField("Post date") body= StreamField([ ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ])
In this example, the body field of BlogPage is defined as a StreamField where authors can compose content from three different block types: headings, paragraphs, and images, which can be used and repeated in any order. The block types available to authors are defined as a list of (name, block_type) tuples: ‘name’ is used to identify the block type within templates, and should follow the standard Python conventions for variable names: lower-case and underscores, no spaces. You can find the complete list of available block types in the StreamField block reference.
Note: StreamField is not a direct replacement for other field types such as RichTextField. If you need to migrate an existing field to StreamField, refer to Migrating RichTextFields to StreamField.
Template rendering
StreamField provides an HTML representation for the stream content as a whole, as well as for each individual block. To include this HTML into your page, use the {% include_block %} tag:
{% load wagtailcore_tags %}
...
{% include_block page.body %}
In the default rendering, each block of the stream is wrapped in a
element (where my_block_name is the block name given in the StreamField definition). If you wish to provide your
1.2. Usage guide 71 Wagtail Documentation, Release 2.15a0 own HTML markup, you can instead iterate over the field’s value, and invoke {% include_block %} on each block in turn:
{% load wagtailcore_tags %}
...
{% for block in page.body %} {% include_block block %} {% endfor %}
For more control over the rendering of specific block types, each block object provides block_type and value properties:
{% load wagtailcore_tags %}
...
{% for block in page.body %} {% if block.block_type == 'heading' %}
In addition to using the built-in block types directly within StreamField, it’s possible to construct new block types by combining sub-blocks in various ways. Examples of this could include: • An “image with caption” block consisting of an image chooser and a text field • A “related links” section, where an author can provide any number of links to other pages • A slideshow block, where each slide may be an image, text or video, arranged in any order Once a new block type has been built up in this way, you can use it anywhere where a built-in block type would be used - including using it as a component for yet another block type. For example, you could define an image gallery block where each item is an “image with caption” block.
StructBlock
StructBlock allows you to group several ‘child’ blocks together to be presented as a single block. The child blocks are passed to StructBlock as a list of (name, block_type) tuples:
body= StreamField([ ('person', blocks.StructBlock([ ('first_name', blocks.CharBlock()), ('surname', blocks.CharBlock()), (continues on next page)
72 Chapter 1. Index Wagtail Documentation, Release 2.15a0
When reading back the content of a StreamField (such as when rendering a template), the value of a StructBlock is a dict-like object with keys corresponding to the block names given in the definition:
{% for block in page.body %} {% if block.block_type == 'person' %}
{% else %} (rendering for other block types) {% endif %} {% endfor %}
Subclassing StructBlock
Placing a StructBlock’s list of child blocks inside a StreamField definition can often be hard to read, and makes it difficult for the same block to be reused in multiple places. As an alternative, StructBlock can be subclassed, with the child blocks defined as attributes on the subclass. The ‘person’ block in the above example could be rewritten as: class PersonBlock(blocks.StructBlock): first_name= blocks.CharBlock() surname= blocks.CharBlock() photo= ImageChooserBlock(required= False) biography= blocks.RichTextBlock()
PersonBlock can then be used in a StreamField definition in the same way as the built-in block types: body= StreamField([ ('person', PersonBlock()), ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ])
Block icons
In the menu that content authors use to add new blocks to a StreamField, each block type has an associated icon. For StructBlock and other structural block types, a placeholder icon is used, since the purpose of these blocks is specific to your project. To set a custom icon, pass the option icon as either a keyword argument to StructBlock, or an attribute on a Meta class:
For a list of the recognised icon identifiers, see the UI Styleguide.
ListBlock
ListBlock defines a repeating block, allowing content authors to insert as many instances of a particular block type as they like. For example, a ‘gallery’ block consisting of multiple images can be defined as follows:
When reading back the content of a StreamField (such as when rendering a template), the value of a ListBlock is a list of child values:
{% for block in page.body %} {% if block.block_type == 'gallery' %}
{% for img in block.value %}
{% image img width-400 %}
{% endfor %}
{% else %} (rendering for other block types) {% endif %} {% endfor %}
74 Chapter 1. Index Wagtail Documentation, Release 2.15a0
StreamBlock
StreamBlock defines a set of child block types that can be mixed and repeated in any sequence, via the same mechanism as StreamField itself. For example, a carousel that supports both image and video slides could be defined as follows:
StreamBlock can also be subclassed in the same way as StructBlock, with the child blocks being specified as attributes on the class: class PersonBlock(blocks.StreamBlock): image= ImageChooserBlock() video= EmbedBlock()
class Meta: icon='image'
A StreamBlock subclass defined in this way can also be passed to a StreamField definition, instead of passing a list of block types. This allows setting up a common set of block types to be used on multiple page types: class CommonContentBlock(blocks.StreamBlock): heading= blocks.CharBlock(form_classname="full title") paragraph= blocks.RichTextBlock() image= ImageChooserBlock() class BlogPage(Page): body= StreamField(CommonContentBlock())
When reading back the content of a StreamField, the value of a StreamBlock is a sequence of block objects with block_type and value properties, just like the top-level value of the StreamField itself.
{% for block in page.body %} {% if block.block_type == 'carousel' %}
{% for slide in block.value %} {% if slide.block_type == 'image' %}
{% image slide.value width-200 %}
{% else %}
class="video">{% include_block slide %}
{% endif %} {% endfor %}
{% else %} (rendering for other block types) {% endif %} (continues on next page)
By default, a StreamField can contain an unlimited number of blocks. The min_num and max_num options on StreamField or StreamBlock allow you to set a minimum or maximum number of blocks: body= StreamField([ ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], min_num=2, max_num=5)
Or equivalently: class CommonContentBlock(blocks.StreamBlock): heading= blocks.CharBlock(form_classname="full title") paragraph= blocks.RichTextBlock() image= ImageChooserBlock()
class Meta: min_num=2 max_num=5
The block_counts option can be used to set a minimum or maximum count for specific block types. This accepts a dict, mapping block names to a dict containing either or both of min_num and max_num. For example, to permit between 1 and 3 ‘heading’ blocks: body= StreamField([ ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ], block_counts={ 'heading':{'min_num':1,'max_num':3}, })
Or equivalently: class CommonContentBlock(blocks.StreamBlock): heading= blocks.CharBlock(form_classname="full title") paragraph= blocks.RichTextBlock() image= ImageChooserBlock()
class Meta: block_counts={ 'heading':{'min_num':1,'max_num':3}, }
Per-block templates
By default, each block is rendered using simple, minimal HTML markup, or no markup at all. For example, a CharBlock value is rendered as plain text, while a ListBlock outputs its child blocks in a
wrapper. To override
76 Chapter 1. Index Wagtail Documentation, Release 2.15a0 this with your own custom HTML rendering, you can pass a template argument to the block, giving the filename of a template file to be rendered. This is particularly useful for custom block types derived from StructBlock:
Or, when defined as a subclass of StructBlock: class PersonBlock(blocks.StructBlock): first_name= blocks.CharBlock() surname= blocks.CharBlock() photo= ImageChooserBlock(required= False) biography= blocks.RichTextBlock()
class Meta: template='myapp/blocks/person.html' icon='user'
Within the template, the block value is accessible as the variable value:
{% load wagtailimages_tags %}
{% image value.photo width-400 %}
{{ value.first_name }}{{ value.surname }}
{{ value.biography }}
Since first_name, surname, photo and biography are defined as blocks in their own right, this could also be written as:
Writing {{ my_block }} is roughly equivalent to {% include_block my_block %}, but the short form is more restrictive, as it does not pass variables from the calling template such as request or page; for this reason, it is recommended that you only use it for simple values that do not render HTML of their own. For example, if our PersonBlock used the template:
then the request.user.is_authenticated test would not work correctly when rendering the block through a {{ ... }} tag:
{# Incorrect: #}
{% for block in page.body %} {% if block.block_type == 'person' %}
{{ block }}
{% endif %} {% endfor %}
{# Correct: #}
{% for block in page.body %} {% if block.block_type == 'person' %}
{% include_block block %}
{% endif %} {% endfor %}
Like Django’s {% include %} tag, {% include_block %} also allows passing additional variables to the included template, through the syntax {% include_block my_block with foo="bar" %}:
{# In page template: #}
{% for block in page.body %} {% if block.block_type == 'person' %} {% include_block block with classname="important" %} {% endif %} {% endfor %}
{# In PersonBlock template: #}
...
The syntax {% include_block my_block with foo="bar" only %} is also supported, to specify that no variables from the parent template other than foo will be passed to the child template. As well as passing variables from the parent template, block subclasses can pass additional template variables of their own by overriding the get_context method:
import datetime
class EventBlock(blocks.StructBlock): (continues on next page)
78 Chapter 1. Index Wagtail Documentation, Release 2.15a0
(continued from previous page) title= blocks.CharBlock() date= blocks.DateBlock()
In this example, the variable is_happening_today will be made available within the block template. The parent_context keyword argument is available when the block is rendered through an {% include_block %} tag, and is a dict of variables passed from the calling template. All block types, not just StructBlock, support the template property. However, for blocks that handle basic Python data types, such as CharBlock and IntegerBlock, there are some limitations on where the template will take effect. For further details, see About StreamField BoundBlocks and values.
Customisations
All block types implement a common API for rendering their front-end and form representations, and storing and retrieving values to and from the database. By subclassing the various block classes and overriding these methods, all kinds of customisations are possible, from modifying the layout of StructBlock form fields to implementing completely new ways of combining blocks. For further details, see How to build custom StreamField blocks.
Modifying StreamField data
A StreamField’s value behaves as a list, and blocks can be inserted, overwritten and deleted before saving the instance back to the database. A new item can be written to the list as a tuple of (block_type, value) - when read back, it will be returned as a BoundBlock object.
# Replace the first block with a new block of type 'heading' my_page.body[0]=('heading',"My story")
# Delete the last block del my_page.body[-1]
# Append a block to the stream my_page.body.append(('paragraph',"
And they all lived happily ever after.
"))
# Save the updated data back to the database my_page.save()
Migrating RichTextFields to StreamField
If you change an existing RichTextField to a StreamField, the database migration will complete with no errors, since both fields use a text column within the database. However, StreamField uses a JSON representation for its data, so the existing text requires an extra conversion step in order to become accessible again. For this to work, the StreamField needs to include a RichTextBlock as one of the available block types. (When updating the model, don’t forget to change FieldPanel to StreamFieldPanel too.) Create the migration as normal using ./manage. py makemigrations, then edit it as follows (in this example, the ‘body’ field of the demo.BlogPage model is being converted to a StreamField with a RichTextBlock named rich_text):
#-*- coding: utf-8 -*- from django.db import models, migrations from wagtail.core.rich_text import RichText def convert_to_streamfield(apps, schema_editor): BlogPage= apps.get_model("demo","BlogPage") for page in BlogPage.objects.all(): if page.body.raw_text and not page.body: page.body=[('rich_text', RichText(page.body.raw_text))] page.save() def convert_to_richtext(apps, schema_editor): BlogPage= apps.get_model("demo","BlogPage") for page in BlogPage.objects.all(): if page.body.raw_text is None: raw_text=''.join([ child.value.source for child in page.body if child.block_type =='rich_text' ]) page.body= raw_text page.save() class Migration(migrations.Migration):
dependencies=[ # leave the dependency line from the generated migration intact! ('demo','0001_initial'), ]
Note that the above migration will work on published Page objects only. If you also need to migrate draft pages and page revisions, then edit the migration as in the following example instead:
#-*- coding: utf-8 -*- import json from django.core.serializers.json import DjangoJSONEncoder from django.db import migrations, models from wagtail.core.rich_text import RichText (continues on next page)
80 Chapter 1. Index Wagtail Documentation, Release 2.15a0
(continued from previous page) def page_to_streamfield(page): changed= False if page.body.raw_text and not page.body: page.body=[('rich_text',{'rich_text': RichText(page.body.raw_text)})] changed= True return page, changed def pagerevision_to_streamfield(revision_data): changed= False body= revision_data.get('body') if body: try: json.loads(body) except ValueError: revision_data['body']= json.dumps( [{ "value":{"rich_text": body}, "type":"rich_text" }], cls=DjangoJSONEncoder) changed= True else: # It's already valid JSON. Leave it. pass return revision_data, changed def page_to_richtext(page): changed= False if page.body.raw_text is None: raw_text=''.join([ child.value['rich_text'].source for child in page.body if child.block_type =='rich_text' ]) page.body= raw_text changed= True return page, changed def pagerevision_to_richtext(revision_data): changed= False body= revision_data.get('body','definitely non-JSON string') if body: try: body_data= json.loads(body) except ValueError: # It's not apparently a StreamField. Leave it. pass else: raw_text=''.join([ child['value']['rich_text'] for child in body_data if child['type'] =='rich_text' ]) revision_data['body']= raw_text (continues on next page)
(continued from previous page) changed= True return revision_data, changed def convert(apps, schema_editor, page_converter, pagerevision_converter): BlogPage= apps.get_model("demo","BlogPage") for page in BlogPage.objects.all():
page, changed= page_converter(page) if changed: page.save()
for revision in page.revisions.all(): revision_data= json.loads(revision.content_json) revision_data, changed= pagerevision_converter(revision_data) if changed: revision.content_json= json.dumps(revision_data,
Wagtail adapts and extends the Django permission system to cater for the needs of website content creation, such as moderation workflows, and multiple teams working on different areas of a site (or multiple sites within the same
82 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Wagtail installation). Permissions can be configured through the ‘Groups’ area of the Wagtail admin interface, under ‘Settings’.
Page permissions
Permissions can be attached at any point in the page tree, and propagate down the tree. For example, if a site had the page tree:
MegaCorp/ About us Offices/ UK France Germany then a group with ‘edit’ permissions on the ‘Offices’ page would automatically receive the ability to edit the ‘UK’, ‘France’ and ‘Germany’ pages. Permissions can be set globally for the entire tree by assigning them on the ‘root’ page - since all pages must exist underneath the root node, and the root cannot be deleted, this permission will cover all pages that exist now and in future. Whenever a user creates a page through the Wagtail admin, that user is designated as the owner of that page. Any user with ‘add’ permission has the ability to edit pages they own, as well as adding new ones. This is in recognition of the fact that creating pages is typically an iterative process involving creating a number of draft versions - giving a user the ability to create a draft but not letting them subsequently edit it would not be very useful. Ability to edit a page also implies the ability to delete it; unlike Django’s standard permission model, there is no distinct ‘delete’ permission. The full set of available permission types is as follows: • Add - grants the ability to create new subpages underneath this page (provided the page model permits this - see Parent page / subpage type rules), and to edit and delete pages owned by the current user. Published pages cannot be deleted unless the user also has ‘publish’ permission. • Edit - grants the ability to edit and delete this page, and any pages underneath it, regardless of ownership. A user with only ‘edit’ permission may not create new pages, only edit existing ones. Published pages cannot be deleted unless the user also has ‘publish’ permission. • Publish - grants the ability to publish and unpublish this page and/or its children. A user without publish permission cannot directly make changes that are visible to visitors of the website; instead, they must submit their changes for moderation. Publish permission is independent of edit permission; a user with only publish permission will not be able to make any edits of their own. • Bulk delete - allows a user to delete pages that have descendants, in a single operation. Without this permission, a user has to delete the descendant pages individually before deleting the parent. This is a safeguard against accidental deletion. This permission must be used in conjunction with ‘add’ / ‘edit’ permission, as it does not provide any deletion rights of its own; it only provides a ‘shortcut’ for the permissions the user has already. For example, a user with just ‘add’ and ‘bulk delete’ permissions will only be able to bulk-delete if all the affected pages are owned by that user, and are unpublished. • Lock - grants the ability to lock or unlock this page (and any pages underneath it) for editing, preventing users from making any further edits to it. Drafts can be viewed only if the user has either Edit or Publish permission.
Image / document permissions
The permission rules for images and documents work on a similar basis to pages. Images and documents are considered to be ‘owned’ by the user who uploaded them; a user with ‘add’ permission also has the ability to edit items they own;
and deletion is considered equivalent to editing rather than having a specific permission type. Access to specific sets of images and documents can be controlled by setting up collections. By default all images and documents belong to the ‘root’ collection, but new collections can be created through the Settings -> Collections area of the admin interface. Permissions set on ‘root’ apply to all collections, so a user with ‘edit’ permission for images on root can edit all images; permissions set on other collections apply to that collection only. The ‘choose’ permission for images and documents determines which collections are visible within the chooser inter- face used to select images and document links for insertion into pages (and other models, such as snippets). Typically, all users are granted choose permission for all collections, allowing them to use any uploaded image or document on pages they create, but this permission can be limited to allow creating collections that are only available for use by specific groups.
Displaying custom permissions in the admin
Most permissions will automatically show up in the wagtail admin Group edit form, however, you can also add them using the register_permissions hook (see register_permissions).
1.3 Advanced topics
1.3.1 Images
Generating renditions in Python
Rendered versions of original images generated by the Wagtail {% image %} template tag are called “renditions”, and are stored as new image files in the site’s [media]/images directory on the first invocation. Image renditions can also be generated dynamically from Python via the native get_rendition() method, for example:
If myimage had a filename of foo.jpg, a new rendition of the image file called foo.fill-300x150. jpegquality-60.jpg would be generated and saved into the site’s [media]/images directory. Argument options are identical to the {% image %} template tag’s filter spec, and should be separated with |. The generated Rendition object will have properties specific to that version of the image, such as url, width and height, so something like this could be used in an API generator, for example:
Properties belonging to the original image from which the generated Rendition was created, such as title, can be accessed through the Rendition’s image property:
84 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Animated GIF support
Pillow, Wagtail’s default image library, doesn’t support animated GIFs. To get animated GIF support, you will have to install Wand. Wand is a binding to ImageMagick so make sure that has been installed as well. When installed, Wagtail will automatically use Wand for resizing GIF files but continue to resize other images with Pillow.
Image file formats
Using the picture element
The picture element can be used with the format- image operation to specify different image formats and let the browser choose the one it prefers. For example:
{% load wagtailimages_tags%}
{% image myimage width-1000 format-webp as image_webp%}
{% image myimage width-1000 format-png as image_png%}
{% image myimage width-1000 format-png%}
Customizing output formats
By default all bmp and webp images are converted to the png format when no image output format is given. The default conversion mapping can be changed by setting the WAGTAILIMAGES_FORMAT_CONVERSIONS to a dictionary which maps the input type to an output type. For example:
will convert bmp images to jpeg and disable the default webp to png conversion.
Custom image models
The Image model can be customised, allowing additional fields to be added to images. To do this, you need to add two models to your project: • The image model itself that inherits from wagtail.images.models.AbstractImage. This is where you would add your additional fields • The renditions model that inherits from wagtail.images.models.AbstractRendition. This is used to store renditions for the new model.
# models.py from django.db import models from wagtail.images.models import Image, AbstractImage, AbstractRendition class CustomImage(AbstractImage): # Add any extra fields to image here
# eg. To add a caption field: # caption = models.CharField(max_length=255, blank=True)
admin_form_fields= Image.admin_form_fields+( # Then add the field names here to make them appear in the form: # 'caption', ) class CustomRendition(AbstractRendition): image= models.ForeignKey(CustomImage, on_delete=models.CASCADE, related_name=
˓→'renditions')
class Meta: unique_together=( ('image','filter_spec','focal_point_key'), )
Then set the WAGTAILIMAGES_IMAGE_MODEL setting to point to it:
WAGTAILIMAGES_IMAGE_MODEL='images.CustomImage'
Migrating from the builtin image model
When changing an existing site to use a custom image model, no images will be copied to the new model automat- ically. Copying old images to the new model would need to be done manually with a data migration. Any templates that reference the builtin image model will still continue to work as before but would need to be updated in order to see any new images.
Referring to the image model wagtail.images.get_image_model() Get the image model from the WAGTAILIMAGES_IMAGE_MODEL setting. Useful for developers making Wagtail plugins that need the image model. Defaults to the standard Image model if no custom model is defined. wagtail.images.get_image_model_string() Get the dotted app.Model name for the image model as a string. Useful for developers making Wagtail plugins that need to refer to the image model, such as in foreign keys, but the model itself is not required.
86 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Changing rich text representation
The HTML representation of an image in rich text can be customised - for example, to display captions or custom fields. To do this requires subclassing Format (see Image Formats in the Rich Text Editor), and overriding its image_to_html method. You may then register formats of your subclass using register_image_format as usual.
# image_formats.py from wagtail.images.formats import Format, register_image_format class SubclassedImageFormat(Format):
As an example, let’s say you want the alt text to be displayed as a caption for the image as well:
# image_formats.py from django.utils.html import format_html from wagtail.images.formats import Format, register_image_format class CaptionedImageFormat(Format):
Wagtail has the ability to automatically detect faces and features inside your images and crop the images to those features. Feature detection uses third-party tools to detect faces/features in an image when the image is uploaded. The detected features are stored internally as a focal point in the focal_point_{x, y, width, height} fields on the Image model. These fields are used by the fill image filter when an image is rendered in a template to crop the image.
Installation
Two third-party tools are known to work with Wagtail: One based on OpenCV for general feature detection and one based on Rustface for face detection.
OpenCV on Debian/Ubuntu
Feature detection requires OpenCV which can be a bit tricky to install as it’s not currently pip-installable. There is more than one way to install these components, but in each case you will need to test that both OpenCV itself and the Python interface have been correctly installed.
Install opencv-python opencv-python is available on PyPI. It includes a Python interface to OpenCV, as well as the statically-built OpenCV binaries themselves. To install:
$ pip install opencv-python
Depending on what else is installed on your system, this may be all that is required. On lighter-weight Linux systems, you may need to identify and install missing system libraries (for example, a slim version of Debian Stretch requires libsm6 libxrender1 libxext6 to be installed with apt).
Install a system-level package
A system-level package can take care of all of the required components. Check what is available for your operating system. For example, python-opencv is available for Debian; it installs OpenCV itself, and sets up Python bindings. However, it may make incorrect assumptions about how you’re using Python (for example, which version you’re using) - test as described below.
Testing the installation
Test the installation:
python3 >>> import cv2
An error such as:
88 Chapter 1. Index Wagtail Documentation, Release 2.15a0
ImportError: libSM.so.6: cannot open shared object file: No such file or directory indicates that a required system library (in this case libsm6) has not been installed. On the other hand,
ModuleNotFoundError: No module named'cv2' means that the Python components have not been set up correctly in your Python environment. If you don’t get an import error, installation has probably been successful.
Rustface
Rustface is Python library with prebuilt wheel files provided for Linux and macOS. Although implemented in Rust it is pip-installable:
$ pip install wheel $ pip install rustface
Registering with Willow
Rustface provides a plug-in that needs to be registered with Willow. This should be done somewhere that gets run on application startup: from willow.registry import registry import rustface.willow registry.register_plugin(rustface.willow)
For example, in an app’s AppConfig.ready.
Cropping
The face detection algorithm produces a focal area that is tightly cropped to the face rather than the whole head. For images with a single face this can be okay in some cases, e.g. thumbnails, it might be overly tight for “headshots”. Image renditions can encompass more of the head by reducing the crop percentage (-c), at the end of the resize-rule, down to as low as 0%:
{% image page.photo fill-200x200-c0 %}
Switching on feature detection in Wagtail
Once installed, you need to set the WAGTAILIMAGES_FEATURE_DETECTION_ENABLED setting to True to au- tomatically detect faces/features whenever a new image is uploaded in to Wagtail or when an image without a focal point is saved (this is done via a pre-save signal handler):
If you already have images in your Wagtail site and would like to run feature detection on them, or you want to apply feature detection selectively when the WAGTAILIMAGES_FEATURE_DETECTION_ENABLED is set to False you can run it manually using the get_suggested_focal_point() method on the Image model. For example, you can manually run feature detection on all images by running the following code in the python shell:
from wagtail.images import get_image_model
Image= get_image_model()
for image in Image.objects.all(): if not image.has_focal_point(): image.set_focal_point(image.get_suggested_focal_point()) image.save()
Dynamic image serve view
In most cases, developers wanting to generate image renditions in Python should use the get_rendition() method. See Generating renditions in Python. If you need to be able to generate image versions for an external system such as a blog or mobile app, Wagtail provides a view for dynamically generating renditions of images by calling a unique URL. The view takes an image id, filter spec and security signature in the URL. If these parameters are valid, it serves an image file matching that criteria. Like the {% image %} tag, the rendition is generated on the first call and subsequent calls are served from a cache.
Setup
Add an entry for the view into your URLs configuration:
90 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Image URL generator UI
When the dynamic serve view is enabled, an image URL generator in the admin interface becomes available automat- ically. This can be accessed through the edit page of any image by clicking the “URL generator” button on the right hand side. This interface allows editors to generate URLs to cropped versions of the image.
Generating dynamic image URLs in Python
Dynamic image URLs can also be generated using Python code and served to a client over an API or used directly in the template. One advantage of using dynamic image URLs in the template is that they do not block the initial response while rendering like the {% image %} tag does. The generate_image_url function in wagtail.images.views.serve is a convenience method to gener- ate a dynamic image URL. Here’s an example of this being used in a view:
By default, the view will serve the image file directly. This behaviour can be changed to a 301 redirect instead which may be useful if you host your images externally. To enable this, pass action='redirect' into the ServeView.as_view() method in your urls configuration: from wagtail.images.views.serve import ServeView urlpatterns=[ ...
Integration with django-sendfile django-sendfile offloads the job of transferring the image data to the web server instead of serving it directly from the Django application. This could greatly reduce server load in situations where your site has many images being downloaded but you’re unable to use a Caching proxy or a CDN. You firstly need to install and configure django-sendfile and configure your web server to use it. If you haven’t done this already, please refer to the installation docs. To serve images with django-sendfile, you can use the SendFileView class. This view can be used out of the box: from wagtail.images.views.serve import SendFileView urlpatterns=[ ...
You can customise it to override the backend defined in the SENDFILE_BACKEND setting: from wagtail.images.views.serve import SendFileView from project.sendfile_backends import MyCustomBackend class MySendFileView(SendFileView): backend= MyCustomBackend
You can also customise it to serve private files. For example, if the only need is to be authenticated (e.g. for Django >= 1.9): from django.contrib.auth.mixins import LoginRequiredMixin from wagtail.images.views.serve import SendFileView class PrivateSendFileView(LoginRequiredMixin, SendFileView): raise_exception= True
92 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Focal points
Focal points are used to indicate to Wagtail the area of an image that contains the subject. This is used by the fill filter to focus the cropping on the subject, and avoid cropping into it. Focal points can be defined manually by a Wagtail user, or automatically by using face or feature detection.
Setting the background-position inline style based on the focal point
When using a Wagtail image as the background of an element, you can use the .background_position_style attribute on the rendition to position the rendition based on the focal point in the image:
{% image page.image width-1024 as image %}
Accessing the focal point in templates
New in version 2.14. You can access the focal point in the template by accessing the .focal_point attribute of a rendition:
{% load wagtailimages %}
{% image myimage width-800 as myrendition %}
1.3.2 Documents
Custom document model
An alternate Document model can be used to add custom behaviour and additional fields. You need to complete the following steps in your project to do this: • Create a new document model that inherits from wagtail.documents.models.AbstractDocument. This is where you would add additional fields. • Point WAGTAILDOCS_DOCUMENT_MODEL to the new model. Here’s an example:
# models.py from wagtail.documents.models import Document, AbstractDocument
class CustomDocument(AbstractDocument): # Custom field example: source= models.CharField( max_length=255, blank=True, null=True )
admin_form_fields= Document.admin_form_fields+( # Add all custom fields names to make them appear in the form: 'source', )
Then in your settings module:
# Ensure that you replace app_label with the app you placed your custom # model in. WAGTAILDOCS_DOCUMENT_MODEL='app_label.CustomDocument'
Migrating from the builtin document model
When changing an existing site to use a custom document model, no documents will be copied to the new model automatically. Copying old documents to the new model would need to be done manually with a data migration. Any templates that reference the builtin document model will still continue to work as before.
Referring to the document model
wagtail.documents.get_document_model() Get the document model from the WAGTAILDOCS_DOCUMENT_MODEL setting. Defaults to the standard Document model if no custom model is defined. wagtail.documents.get_document_model_string() Get the dotted app.Model name for the document model as a string. Useful for developers making Wagtail plugins that need to refer to the document model, such as in foreign keys, but the model itself is not required.
1.3.3 Embedded content
Wagtail supports generating embed code from URLs to content on external providers such as Youtube or Twitter. By default, Wagtail will fetch the embed code directly from the relevant provider’s site using the oEmbed protocol. Wagtail has a built-in list of the most common providers and this list can be changed with a setting. Wagtail also supports fetching embed code using Embedly and custom embed finders.
Embedding content on your site
Wagtail’s embeds module should work straight out of the box for most providers. You can use any of the following methods to call the module:
94 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Rich text
Wagtail’s default rich text editor has a “media” icon that allows embeds to be placed into rich text. You don’t have to do anything to enable this; just make sure the rich text field’s content is being passed through the |richtext filter in the template as this is what calls the embeds module to fetch and nest the embed code.
EmbedBlock StreamField block type
The EmbedBlock block type allows embeds to be placed into a StreamField. The max_width and max_height arguments are sent to the provider when fetching the embed code. For example: from wagtail.embeds.blocks import EmbedBlock class MyStreamField(blocks.StreamBlock): ...
embed= EmbedBlock(max_width=800, max_height=400)
{% embed %} tag
Syntax: {% embed [max_width=] %} You can nest embeds into a template by passing the URL and an optional max_width argument to the {% embed %} tag. The max_width argument is sent to the provider when fetching the embed code.
{% load wagtailembeds_tags %}
{# Embed a YouTube video #} {% embed 'https://www.youtube.com/watch?v=Ffu-2jEdLPw' %}
{# This tag can also take the URL from a variable #} {% embed page.video_url %}
From Python
You can also call the internal get_embed function that takes a URL string and returns an Embed object (see model documentation below). This also takes a max_width keyword argument that is sent to the provider when fetching the embed code. from wagtail.embeds.embeds import get_embed from wagtail.embeds.exceptions import EmbedException try: embed= get_embed('https://www.youtube.com/watch?v=Ffu-2jEdLPw')
Embed finders are the modules within Wagtail that are responsible for producing embed code from a URL. Embed finders are configured using the WAGTAILEMBEDS_FINDERS setting. This is a list of finder configurations that are each run in order until one of them successfully returns an embed: The default configuration is:
The default embed finder fetches the embed code directly from the content provider using the oEmbed protocol. Wagtail has a built-in list of providers which are all enabled by default. You can find that provider list at the following link: https://github.com/wagtail/wagtail/blob/main/wagtail/embeds/oembed_providers.py
Customising the provider list
You can limit which providers may be used by specifying the list of providers in the finder configuration. For example, this configuration will only allow content to be nested from Vimeo and Youtube. It also adds a custom provider:
from wagtail.embeds.oembed_providers import youtube, vimeo
# Add a custom provider # Your custom provider must support oEmbed for this to work. You should be # able to find these details in the provider's documentation. # - 'endpoint' is the URL of the oEmbed endpoint that Wagtail will call # - 'urls' specifies which patterns my_custom_provider={ 'endpoint':'https://customvideosite.com/oembed', 'urls':[ '^http(?:s)?://(?:www\\.)?customvideosite\\.com/[^#?/]+/videos/.+$', ] }
Multiple finders can be chained together. This can be used for customising the configuration for one provider without affecting the others.
96 Chapter 1. Index Wagtail Documentation, Release 2.15a0
For example, this is how you can instruct Youtube to return videos in HTTPS (which must be done explicitly for YouTube): from wagtail.embeds.oembed_providers import youtube
WAGTAILEMBEDS_FINDERS=[ # Fetches YouTube videos but puts ``?scheme=https`` in the GET parameters # when calling YouTube's oEmbed endpoint { 'class':'wagtail.embeds.finders.oembed', 'providers': [youtube], 'options':{'scheme':'https'} },
# Handles all other oEmbed providers the default way { 'class':'wagtail.embeds.finders.oembed', } ]
How Wagtail uses multiple finders
If multiple providers can handle a URL (for example, a YouTube video was requested using the configuration above), the topmost finder is chosen to perform the request. Wagtail will not try to run any other finder, even if the chosen one didn’t return an embed.
Facebook and Instagram
As of October 2020, Facebook deprecated their public oEmbed APIs. If you would like to embed Facebook or In- stagram posts in your site, you will need to use the new authenticated APIs. This requires you to set up a Facebook Developer Account and create a Facebook App that includes the oEmbed Product. Instructions for creating the neces- sary app are in the requirements sections of the Facebook and Instagram documentation. As of June 2021, the oEmbed Product has been replaced with the oEmbed Read feature. In order to embed Facebook and Instagram posts your app must activate the oEmbed Read feature. Furthermore the app must be reviewed and accepted by Facebook. You can find the announcement in the API changelog. Apps that activated the oEmbed Product before June 8, 2021 need to activate the oEmbed Read feature and review their app before September 7, 2021. Once you have your app access tokens (App ID and App Secret), add the Facebook and/or Instagram finders to your WAGTAILEMBEDS_FINDERS setting and configure them with the App ID and App Secret from your app:
# Handles all other oEmbed providers the default way { 'class':'wagtail.embeds.finders.oembed', } ]
By default, Facebook and Instagram embeds include some JavaScript that is necessary to fully render the embed. In certain cases, this might not be something you want - for example, if you have multiple Facebook embeds, this would result in multiple script tags. By passing 'omitscript': True in the configuration, you can indicate that these script tags should be omitted from the embed HTML. Note that you will then have to take care of loading this script yourself.
Embed.ly
Embed.ly is a paid-for service that can also provide embeds for sites that do not implement the oEmbed protocol. They also provide some helpful features such as giving embeds a consistent look and a common video playback API which is useful if your site allows videos to be hosted on different providers and you need to implement custom controls for them. Wagtail has built in support for fetching embeds from Embed.ly. To use it, first pip install the Embedly python package. Now add an embed finder to your WAGTAILEMBEDS_FINDERS setting that uses the wagtail.embeds. finders.oembed class and pass it your API key:
For complete control, you can create a custom finder class. Here’s a stub finder class that could be used as a skeleton; please read the docstrings for details of what each method does:
from wagtail.embeds.finders.base import EmbedFinder class ExampleFinder(EmbedFinder): def __init__(self, **options): pass
def accept(self, url): """ Returns True if this finder knows how to fetch an embed for the URL.
This should not have any side effects (no requests to external servers) (continues on next page)
98 Chapter 1. Index Wagtail Documentation, Release 2.15a0
(continued from previous page) """ pass
def find_embed(self, url, max_width=None): """ Takes a URL and max width and returns a dictionary of information about the content to be used for embedding it on the site.
This is the part that may make requests to external APIs. """ # TODO: Perform the request
return { 'title':"Title of the content", 'author_name':"Author name", 'provider_name':"Provider name (eg. YouTube, Vimeo, etc)", 'type':"Either'photo','video','link' or'rich'", 'thumbnail_url':"URL to thumbnail image", 'width': width_in_pixels, 'height': height_in_pixels, 'html':"
The Embed HTML
", }
Once you’ve implemented all of those methods, you just need to add it to your WAGTAILEMBEDS_FINDERS setting:
WAGTAILEMBEDS_FINDERS=[ { 'class':'path.to.your.finder.class.here', # Any other options will be passed as kwargs to the __init__ method } ]
The Embed model class wagtail.embeds.models.Embed Embeds are fetched only once and stored in the database so subsequent requests for an individual embed do not hit the embed finders again. url (text) The URL of the original content of this embed. max_width (integer, nullable) The max width that was requested. type (text) The type of the embed. This can be either ‘video’, ‘photo’, ‘link’ or ‘rich’. html (text) The HTML content of the embed that should be placed on the page
title (text) The title of the content that is being embedded. author_name (text) The author name of the content that is being embedded. provider_name (text) The provider name of the content that is being embedded. For example: YouTube, Vimeo thumbnail_url (text) a URL to a thumbnail image of the content that is being embedded. width (integer, nullable) The width of the embed (images and videos only). height (integer, nullable) The height of the embed (images and videos only). last_updated (datetime) The Date/time when this embed was last fetched.
Deleting embeds
As long as your embeds configuration is not broken, deleting items in the Embed model should be perfectly safe to do. Wagtail will automatically repopulate the records that are being used on the site. You may want to do this if you’ve changed from oEmbed to Embedly or vice-versa as the embed code they generate may be slightly different and lead to inconsistency on your site.
1.3.4 How to add Wagtail into an existing Django project
To install Wagtail completely from scratch, create a new Django project and an app within that project. For instructions on these tasks, see Writing your first Django app. Your project directory will look like the following:
myproject/ myproject/ __init__.py settings.py urls.py wsgi.py myapp/ __init__.py models.py tests.py (continues on next page)
100 Chapter 1. Index Wagtail Documentation, Release 2.15a0
(continued from previous page) admin.py views.py manage.py
From your app directory, you can safely remove admin.py and views.py, since Wagtail will provide this function- ality for your models. Configuring Django to load Wagtail involves adding modules and variables to settings.py and URL configuration to urls.py. For a more complete view of what’s defined in these files, see Django Settings and Django URL Dispatcher. What follows is a settings reference which skips many boilerplate Django settings. If you just want to get your Wagtail install up quickly without fussing with settings at the moment, see Ready to Use Example Configuration Files.
Wagtail depends on the default set of Django middleware modules, to cover basic security and functionality such as login sessions. One additional middleware module is provided: RedirectMiddleware Wagtail provides a simple interface for adding arbitrary redirects to your site and this module makes it happen.
(continued from previous page) 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
Wagtail requires several Django app modules, third-party apps, and defines several apps of its own. Wagtail was built to be modular, so many Wagtail apps can be omitted to suit your needs. Your own app (here myapp) is where you define your models, templates, static assets, template tags, and other custom functionality for your site.
Wagtail Apps wagtail.core The core functionality of Wagtail, such as the Page class, the Wagtail tree, and model fields. wagtail.admin The administration interface for Wagtail, including page edit handlers. wagtail.documents The Wagtail document content type. wagtail.snippets Editing interface for non-Page models and objects. See Snippets. wagtail.users User editing interface. wagtail.images The Wagtail image content type. wagtail.embeds Module governing oEmbed and Embedly content in Wagtail rich text fields. See Inserting videos into body content. wagtail.search Search framework for Page content. See Search. wagtail.sites Management UI for Wagtail sites. wagtail.contrib.redirects Admin interface for creating arbitrary redirects on your site. wagtail.contrib.forms Models for creating forms on your pages and viewing submissions. See Form builder.
Third-Party Apps taggit Tagging framework for Django. This is used internally within Wagtail for image and document tagging and is available for your own models as well. See Tagging for a Wagtail model recipe or the Taggit Documentation. modelcluster Extension of Django ForeignKey relation functionality, which is used in Wagtail pages for on- the-fly related object creation. For more information, see Inline Panels and Model Clusters or the django- modelcluster github project page.
URL Patterns
from django.contrib import admin
from wagtail.core import urls as wagtail_urls from wagtail.admin import urls as wagtailadmin_urls from wagtail.documents import urls as wagtaildocs_urls
path('admin/', include(wagtailadmin_urls)), (continues on next page)
102 Chapter 1. Index Wagtail Documentation, Release 2.15a0
(continued from previous page) path('documents/', include(wagtaildocs_urls)),
# Optional URL for including your own vanilla Django urls/views re_path(r'', include('myapp.urls')),
# For anything not caught by a more specific rule above, hand over to # Wagtail's serving mechanism re_path(r'', include(wagtail_urls)), ]
This block of code for your project’s urls.py does a few things: • Load the vanilla Django admin interface to /django-admin/ • Load the Wagtail admin and its various apps • Dispatch any vanilla Django apps you’re using other than Wagtail which require their own URL configuration (this is optional, since Wagtail might be all you need) • Lets Wagtail handle any further URL dispatching. That’s not everything you might want to include in your project’s URL configuration, but it’s what’s necessary for Wagtail to flourish.
Ready to Use Example Configuration Files
These two files should reside in your project directory (myproject/myproject/). settings.py
DATABASES={ 'default':{ 'ENGINE':'django.db.backends.postgresql', 'NAME':'myprojectdb', 'USER':'postgres', 'PASSWORD':'', 'HOST':'', # Set to empty string for localhost. 'PORT':'', # Set to empty string for default. 'CONN_MAX_AGE': 600, # number of seconds database connections should persist
˓→for } (continues on next page)
104 Chapter 1. Index Wagtail Documentation, Release 2.15a0
# Default to dummy email backend. Configure dev/production/local backend # as per https://docs.djangoproject.com/en/stable/topics/email/#email-backends EMAIL_BACKEND='django.core.mail.backends.dummy.EmailBackend'
# Hosts/domain names that are valid for this site; required if DEBUG is False ALLOWED_HOSTS=[]
# Make this unique, and don't share it with anybody. SECRET_KEY='change-me'
EMAIL_SUBJECT_PREFIX='[Wagtail]'
INTERNAL_IPS=('127.0.0.1','10.0.2.2')
# A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See https://docs.djangoproject.com/en/stable/topics/logging for # more details on how to customize your logging configuration. LOGGING={ 'version':1, 'disable_existing_loggers': False, 'filters':{ (continues on next page)
# Wagtail email notification format # WAGTAILADMIN_NOTIFICATION_USE_HTML = True
# Reverse the default case-sensitive handling of tags TAGGIT_CASE_INSENSITIVE= True urls.py from django.urls import include, path, re_path from django.conf.urls.static import static from django.views.generic.base import RedirectView from django.contrib import admin from django.conf import settings import os.path from wagtail.core import urls as wagtail_urls (continues on next page)
106 Chapter 1. Index Wagtail Documentation, Release 2.15a0
(continued from previous page) from wagtail.admin import urls as wagtailadmin_urls from wagtail.documents import urls as wagtaildocs_urls urlpatterns=[ path('django-admin/', admin.site.urls),
# For anything not caught by a more specific rule above, hand over to # Wagtail's serving mechanism re_path(r'', include(wagtail_urls)), ] if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns+= staticfiles_urlpatterns() # tell gunicorn where static files are
˓→in dev mode urlpatterns+= static(settings.MEDIA_URL+'images/', document_root=os.path.
Wagtail is straightforward to deploy on modern Linux-based distributions, and should run with any of the combinations detailed in Django’s deployment documentation. See the section on performance for the non-Python services we recommend.
Divio Cloud is a Dockerised cloud hosting platform for Python/Django that allows you to launch and deploy Wagtail projects in minutes. With a free account, you can create a Wagtail project. Choose from a: • site based on the Wagtail Bakery project, or • brand new Wagtail project (see the how to get started notes). Divio Cloud also hosts a live Wagtail Bakery demo (no account required).
On PythonAnywhere
PythonAnywhere is a Platform-as-a-Service (PaaS) focused on Python hosting and development. It allows developers to quickly develop, host, and scale applications in a cloud environment. Starting with a free plan they also provide MySQL and PostgreSQL databases as well as very flexible and affordable paid plans, so there’s all you need to host a Wagtail site. To get quickly up and running you may use the wagtail-pythonanywhere-quickstart.
Google Cloud is an Infrastructure-as-a-Service (IaaS) that offers multiple managed products, supported by Python client libraries, to help you build, deploy, and monitor your applications. You can deploy Wagtail, or any Django application, in a number of ways, including on App Engine or Cloud Run.
On other PAASs and IAASs
We know of Wagtail sites running on Heroku, Digital Ocean and elsewhere. If you have successfully installed Wagtail on your platform or infrastructure, please contribute your notes to this documentation!
Deployment tips
Static files
As with all Django projects, static files are not served by the Django application server in production (i.e. outside of the manage.py runserver command); these need to be handled separately at the web server level. See Django’s documentation on deploying static files. The JavaScript and CSS files used by the Wagtail admin frequently change between releases of Wagtail - it’s important to avoid serving outdated versions of these files due to browser or server-side caching, as this can cause hard-to- diagnose issues. We recommend enabling ManifestStaticFilesStorage in the STATICFILES_STORAGE setting - this ensures that different versions of files are assigned distinct URLs.
Cloud storage
Wagtail follows Django’s conventions for managing uploaded files, and can be configured to store uploaded images and documents on a cloud storage service such as Amazon S3; this is done through the DEFAULT_FILE_STORAGE setting in conjunction with an add-on package such as django-storages. Be aware that setting up remote storage will not entirely offload file handling tasks from the application server - some Wagtail functionality requires files to be read back by the application server. In particular, original image files need to be read back whenever a new resized rendition is created, and documents may be configured to be served through a Django view in order to enforce permission checks (see WAGTAILDOCS_SERVE_METHOD). Note that the django-storages Amazon S3 backends (storages.backends.s3boto.S3BotoStorage and storages.backends.s3boto3.S3Boto3Storage) do not correctly handle duplicate filenames in their default configuration. When using these backends, AWS_S3_FILE_OVERWRITE must be set to False. If you are also serving Wagtail’s static files from remote storage (using Django’s STATICFILES_STORAGE setting), you’ll need to ensure that it is configured to serve CORS HTTP headers, as current browsers will reject remotely- hosted font files that lack a valid header. For Amazon S3, refer to the documentation Setting Bucket and Object Access Permissions, or (for the storages.backends.s3boto.S3Boto3Storage backend only) add the following to your Django settings:
AWS_S3_OBJECT_PARAMETERS={ "ACL":"public-read" }
The ACL parameter accepts a list of predefined configurations for Amazon S3. For more information, refer to the documentation Canned ACL. For Google Cloud Storage, create a cors.json configuration:
108 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Then, apply this CORS configuration to the storage bucket:
gsutil cors set cors.json gs://$GS_BUCKET_NAME
For other storage services, refer to your provider’s documentation, or the documentation for the Django storage back- end library you’re using.
1.3.6 Performance
Wagtail is designed for speed, both in the editor interface and on the front-end, but if you want even better performance or you need to handle very high volumes of traffic, here are some tips on eking out the most from your installation.
Editor interface
We have tried to minimise external dependencies for a working installation of Wagtail, in order to make it as simple as possible to get going. However, a number of default settings can be configured for better performance:
Cache
We recommend Redis as a fast, persistent cache. Install Redis through your package manager (on Debian or Ubuntu: sudo apt-get install redis-server), add django-redis to your requirements.txt, and enable it as a cache backend:
If you define a cache named ‘renditions’ (typically alongside your ‘default’ cache), Wagtail will cache image rendition lookups, which may improve the performance of pages which include many images.
Wagtail has strong support for Elasticsearch - both in the editor interface and for users of your site - but can fall back to a database search if Elasticsearch isn’t present. Elasticsearch is faster and more powerful than the Django ORM for text search, so we recommend installing it or using a hosted service like Searchly. For details on configuring Wagtail for Elasticsearch, see Elasticsearch Backend.
Database
Wagtail is tested on PostgreSQL, SQLite and MySQL. It may work on some third-party database backends as well, but this is not guaranteed. We recommend PostgreSQL for production use.
Templates
The overhead from reading and compiling templates adds up. Django wraps its default loaders with cached template loader: which stores the compiled Template in memory and returns it for subsequent requests. The cached loader is automatically enabled when DEBUG is False. If you are using custom loaders, update your settings to use it:
110 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Caching proxy
To support high volumes of traffic with excellent response times, we recommend a caching proxy. Both Varnish and Squid have been tested in production. Hosted proxies like Cloudflare should also work well. Wagtail supports automatic cache invalidation for Varnish/Squid. See Frontend cache invalidator for more information.
* Page structure * How locales and translations are recorded in the database * Translated homepages * Language detection and routing – Configuration
* Enabling internationalisation * Configuring available languages * Enabling the locale management UI (optional) * Adding a language prefix to URLs * User language auto-detection * Custom routing/language detection – Recipes for internationalised sites
* Language/region selector * API filters for headless sites * Translatable snippets – Translation workflow
* Wagtail Localize • Alternative internationalisation plugins • Wagtail admin translations • Change Wagtail admin language on a per-user basis • Changing the primary language of your Wagtail installation
Out of the box, Wagtail assumes all content will be authored in a single language. This document describes how to configure Wagtail for authoring content in multiple languages.
Note: Wagtail provides the infrastructure for creating and serving content in multiple languages. There are two options for managing translations across different languages in the admin interface: wagtail.contrib.simple_translation or the more advanced wagtail-localize (third-party package).
This document only covers the internationalisation of content managed by Wagtail. For information on how to translate static content in template files, JavaScript code, etc, refer to the Django internationalisation docs. Or, if you are building a headless site, refer to the docs of the frontend framework you are using.
Wagtail’s approach to multi-lingual content
This section provides an explanation of Wagtail’s internationalisation approach. If you’re in a hurry, you can skip to Configuration. In summary: • Wagtail stores content in a separate page tree for each locale • It has a built-in Locale model and all pages are linked to a Locale with the locale foreign key field • It records which pages are translations of each other using a shared UUID stored in the translation_key field • It automatically routes requests through translations of the site’s homepage • It uses Django’s i18n_patterns and LocaleMiddleware for language detection
Page structure
Wagtail stores content in a separate page tree for each locale. For example, if you have two sites in two locales, then you will see four homepages at the top level of the page hierarchy in the explorer. This approach has some advantages for the editor experience as well: • There is no default language for editing, so content can be authored in any language and then translated to any other. • Translations of a page are separate pages so they can be published at different times. • Editors can be given permission to edit content in one locale and not others.
How locales and translations are recorded in the database
All pages (and any snippets that have translation enabled) have a locale and translation_key field: • locale is a foreign key to the Locale model • translation_key is a UUID that’s used to find translations of a piece of content. Translations of the same page/snippet share the same value in this field These two fields have a ‘unique together’ constraint so you can’t have more than one translation in the same locale.
112 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Translated homepages
When you set up a site in Wagtail, you select the site’s homepage in the ‘root page’ field and all requests to that site’s root URL will be routed to that page. Multi-lingual sites have a separate homepage for each locale that exist as siblings in the page tree. Wagtail finds the other homepages by looking for translations of the site’s ‘root page’. This means that to make a site available in another locale, you just need to translate and publish its homepage in that new locale. If Wagtail can’t find a homepage that matches the user’s language, it will fall back to the page that is selected as the ‘root page’ on the site record, so you can use this field to specify the default language of your site.
Language detection and routing
For detecting the user’s language and adding a prefix to the URLs (/en/, /fr-fr/, for example), Wagtail is designed to work with Django’s builtin internationalisation utilities such as i18n_patterns and LocaleMiddleware. This means that Wagtail should work seamlessly with any other internationalised Django applications on your site.
Locales
The locales that are enabled on a site are recorded in the Locale model in wagtailcore. This model has just two fields: ID and language_code which stores the BCP-47 language tag that represents this locale. The locale records can be set up with an optional management UI or created in the shell. The possible values of the language_code field are controlled by the WAGTAIL_CONTENT_LANGUAGES setting.
Note: Read this if you’ve changed LANGUAGE_CODE before enabling internationalisation On initial migration, Wagtail creates a Locale record for the language that was set in the LANGUAGE_CODE setting at the time the migration was run. All pages will be assigned to this Locale when Wagtail’s internationalisation is disabled. If you have changed the LANGUAGE_CODE setting since updating to Wagtail 2.11, you will need to manually update the record in the Locale model too before enabling internationalisation, as your existing content will be assigned to the old code.
Configuration
In this section, we will go through the minimum configuration required to enable content to be authored in multiple languages.
• Enabling internationalisation • Configuring available languages • Enabling the locale management UI (optional) • Adding a language prefix to URLs • User language auto-detection
To enable internationalisation in both Django and Wagtail, set the following settings to True:
# my_project/settings.py
USE_I18N= True WAGTAIL_I18N_ENABLED= True
In addition, you might also want to enable Django’s localisation support. This will make dates and numbers display in the user’s local format:
# my_project/settings.py
USE_L10N= True
Configuring available languages
Next we need to configure the available languages. There are two settings for this that are each used for different purposes: • LANGUAGES - This sets which languages are available on the frontend of the site. • WAGTAIL_CONTENT_LANGUAGES - This sets which the languages Wagtail content can be authored in. You can set both of these settings to the exact same value. For example, to enable English, French, and Spanish:
Note: Whenever WAGTAIL_CONTENT_LANGUAGES is changed, the Locale model needs to be updated as well to match. This can either be done with a data migration or with the optional locale management UI described in the next section.
You can also set these to different values. You might want to do this if you want to have some programmatic localisation (like date formatting or currency, for example) but use the same Wagtail content in multiple regions:
# my_project/settings.py
LANGUAGES=[ ('en-GB',"English (Great Britain)"), ('en-US',"English (United States)"), ('en-CA',"English (Canada)"), ('fr-FR',"French (France)"), ('fr-CA',"French (Canada)"), (continues on next page)
114 Chapter 1. Index Wagtail Documentation, Release 2.15a0
When configured like this, the site will be available in all the different locales in the first list, but there will only be two language trees in Wagtail. All the en- locales will use the “English” language tree, and the fr- locales will use the “French” language tree. The differences between each locale in a language would be programmatic. For example: which date/number format to use, and what currency to display prices in.
Enabling the locale management UI (optional)
An optional locale management app exists to allow a Wagtail administrator to set up the locales from the Wagtail admin interface. To enable it, add wagtail.locales into INSTALLED_APPS:
# my_project/settings.py
INSTALLED_APPS=[ # ... 'wagtail.locales', # ... ]
Adding a language prefix to URLs
To allow all of the page trees to be served at the same domain, we need to add a URL prefix for each language. To implement this, we can use Django’s built-in i18n_patterns function, which adds a language prefix to all of the URL patterns passed into it. This activates the language code specified in the URL and Wagtail takes this into account when it decides how to route the request. In your project’s urls.py add Wagtail’s core URLs (and any other URLs you want to be translated) into an i18n_patterns block:
# /my_project/urls.py
...
from django.conf.urls.i18n import i18n_patterns
# Non-translatable URLs # Note: if you are using the Wagtail API or sitemaps, # these should not be added to `i18n_patterns` either urlpatterns=[ path('django-admin/', admin.site.urls),
path('admin/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), (continues on next page)
# Translatable URLs # These will be available under a language code prefix. For example /en/search/ urlpatterns+= i18n_patterns( path('search/', search_views.search, name='search'), path("", include(wagtail_urls)), )
User language auto-detection
After wrapping your URL patterns with i18n_patterns, your site will now respond on URL prefixes. But now it won’t respond on the root path. To fix this, we need to detect the user’s browser language and redirect them to the best language prefix. The recom- mended approach to do this is with Django’s LocaleMiddleware:
You don’t strictly have to use i18n_patterns or LocaleMiddleware for this and you can write your own logic if you need to. All Wagtail needs is the language to be activated (using Django’s django.utils.translation.activate function) before the wagtail.core.views.serve view is called.
Recipes for internationalised sites
Language/region selector
Perhaps the most important bit of internationalisation-related UI you can add to your site is a selector to allow users to switch between different languages. If you’re not convinced that you need this, have a look at https://www.w3.org/International/questions/qa-site-conneg# yyyshortcomings for some rationale.
Basic example
Here is a basic example of how to add links between translations of a page. This example, however, will only include languages defined in WAGTAIL_CONTENT_LANGUAGES and not any extra languages that might be defined in LANGUAGES. For more information on what both of these settings mean, see Configuring available languages.
116 Chapter 1. Index Wagtail Documentation, Release 2.15a0
If both settings are set to the same value, this example should work well for you, otherwise skip to the next section that has a more complicated example which takes this into account.
{# make sure these are at the top of the file #} {% load i18n wagtailcore_tags %}
{% if page %} {% for translation in page.get_translations.live %} {% get_language_info for translation.locale.language_code as lang %} {{ lang.name_local }} {% endfor %} {% endif %}
Let’s break this down:
{% if page %} ... {% endif %}
If this is part of a shared base template it may be used in situations where no page object is available, such as 404 error responses, so check that we have a page before proceeding.
{% for translation in page.get_translations.live %} ... {% endfor %}
This for block iterates through all published translations of the current page.
{% get_language_info for translation.locale.language_code as lang %}
This is a Django built-in tag that gets info about the language of the translation. For more information, see get_language_info() in the Django docs.
This adds a link to the translation. We use {{ lang.name_local }} to display the name of the locale in its own language. We also add rel and hreflang attributes to the tag for SEO.
Handling locales that share content
Rather than iterating over pages, this example iterates over all of the configured languages and finds the page for each one. This works better than the Basic example above on sites that have extra Django LANGUAGES that share the same Wagtail content. For this example to work, you firstly need to add Django’s django.template.context_processors.i18n context processor to your TEMPLATES setting:
{% for language_code, language_name in LANGUAGES %} ... {% endfor %}
This for block iterates through all of the configured languages on the site. The LANGUAGES variable comes from the django.template.context_processors.i18n context processor.
{% get_language_info for language_code as lang %}
Does exactly the same as the previous example.
{% language language_code %} ... {% endlanguage %}
This language tag comes from Django’s i18n tag library. It changes the active language for just the code contained within it.
118 Chapter 1. Index Wagtail Documentation, Release 2.15a0
API filters for headless sites
For headless sites, the Wagtail API supports two extra filters for internationalised sites: • ?locale= Filters pages by the given locale • ?translation_of= Filters pages to only include translations of the given page ID For more information, see Special filters for internationalised sites.
Translatable snippets
You can make a snippet translatable by making it inherit from wagtail.core.models.TranslatableMixin. For example:
# myapp/models.py
from django.db import models
from wagtail.core.models import TranslatableMixin from wagtail.snippets.models import register_snippet
@register_snippet class Advert(TranslatableMixin, models.Model): name= models.CharField(max_length=255)
The TranslatableMixin model adds the locale and translation_key fields to the model.
Making snippets with existing data translatable
For snippets with existing data, it’s not possible to just add TranslatableMixin, make a migration, and run it. This is because the locale and translation_key fields are both required and translation_key needs a unique value for each instance. To migrate the existing data properly, we firstly need to use BootstrapTranslatableMixin, which excludes these constraints, then add a data migration to set the two fields, then switch to TranslatableMixin. This is only needed if there are records in the database. So if the model is empty, you can go straight to adding TranslatableMixin and skip this.
Step 1: Add BootstrapTranslatableMixin to the model
This will add the two fields without any constraints:
# myapp/models.py
from django.db import models
from wagtail.core.models import BootstrapTranslatableMixin from wagtail.snippets.models import register_snippet
(continued from previous page) class Advert(BootstrapTranslatableMixin, models.Model): name= models.CharField(max_length=255)
# if the model has a Meta class, ensure it inherits from # BootstrapTranslatableMixin.Meta too class Meta(BootstrapTranslatableMixin.Meta): verbose_name='adverts'
Run python manage.py makemigrations myapp to generate the schema migration.
Step 2: Create a data migration
Create a data migration with the following command: python manage.py makemigrations myapp --empty
This will generate a new empty migration in the app’s migrations folder. Edit that migration and add a BootstrapTranslatableModel for each model to bootstrap in that app: from django.db import migrations from wagtail.core.models import BootstrapTranslatableModel class Migration(migrations.Migration): dependencies=[ ('myapp','0002_bootstraptranslations'), ]
# Add one operation for each model to bootstrap here # Note: Only include models that are in the same app! operations=[ BootstrapTranslatableModel('myapp.Advert'), ]
Repeat this for any other apps that contain a model to be bootstrapped.
Step 3: Change BootstrapTranslatableMixin to TranslatableMixin
Now that we have a migration that fills in the required fields, we can swap out BootstrapTranslatableMixin for TranslatableMixin that has all the constraints:
# myapp/models.py from wagtail.core.models import TranslatableMixin # Change this line
@register_snippet class Advert(TranslatableMixin, models.Model): # Change this line name= models.CharField(max_length=255)
class Meta(TranslatableMixin.Meta): # Change this line, if present verbose_name='adverts'
120 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Step 4: Run makemigrations to generate schema migrations, then migrate!
Run makemigrations to generate the schema migration that adds the constraints into the database, then run migrate to run all of the migrations:
When prompted to select a fix for the nullable field ‘locale’ being changed to non-nullable, select the option “Ignore for now” (as this has been handled by the data migration).
Translation workflow
As mentioned at the beginning, Wagtail does supply wagtail.contrib.simple_translation. The simple_translation module provides a user interface that allows users to copy pages and translatable snippets into another language. • Copies are created in the source language (not translated) • Copies of pages are in draft status Content editors need to translate the content and publish the pages. To enable add "wagtail.contrib.simple_translation" to INSTALLED_APPS and run python manage.py migrate to create the submit_translation permissions. In the Wagtail admin, go to settings and give some users or groups the “Can submit translations” permission.
Note: Simple Translation is optional. It can be switched out by third-party packages. Like the more advanced wagtail-localize.
Wagtail Localize
As part of the initial work on implementing internationalisation for Wagtail core, we also created a translation package called wagtail-localize. This supports translating pages within Wagtail, using PO files, machine translation, and external integration with translation services. Github: https://github.com/wagtail/wagtail-localize
Alternative internationalisation plugins
Before official multi-language support was added into Wagtail, site implementors had to use external plugins. These have not been replaced by Wagtail’s own implementation as they use slightly different approaches, one of them might fit your use case better: • Wagtailtrans • wagtail-modeltranslation For a comparison of these options, see AccordBox’s blog post How to support multi-language in Wagtail CMS.
The Wagtail admin backend has been translated into many different languages. You can find a list of currently available translations on Wagtail’s Transifex page. (Note: if you’re using an old version of Wagtail, this page may not accurately reflect what languages you have available). If your language isn’t listed on that page, you can easily contribute new languages or correct mistakes. Sign up and submit changes to Transifex. Translation updates are typically merged into an official release within one month of being submitted.
Change Wagtail admin language on a per-user basis
Logged-in users can set their preferred language from /admin/account/. By default, Wagtail provides a list of languages that have a >= 90% translation coverage. It is possible to override this list via the WAGTAILAD- MIN_PERMITTED_LANGUAGES setting. In case there is zero or one language permitted, the form will be hidden. If there is no language selected by the user, the LANGUAGE_CODE will be used.
Changing the primary language of your Wagtail installation
The default language of Wagtail is en-us (American English). You can change this by tweaking a couple of Django settings: • Make sure USE_I18N is set to True • Set LANGUAGE_CODE to your websites’ primary language If there is a translation available for your language, the Wagtail admin backend should now be in the language you’ve chosen.
1.3.8 Private pages
Users with publish permission on a page can set it to be private by clicking the ‘Privacy’ control in the top right corner of the page explorer or editing interface. This sets a restriction on who is allowed to view the page and its sub-pages. Several different kinds of restriction are available: • Accessible to logged-in users: The user must log in to view the page. All user accounts are granted access, regardless of permission level. • Accessible with the following password: The user must enter the given password to view the page. This is appropriate for situations where you want to share a page with a trusted group of people, but giving them individual user accounts would be overkill. The same password is shared between all users, and this works independently of any user accounts that exist on the site. • Accessible to users in specific groups: The user must be logged in, and a member of one or more of the specified groups, in order to view the page. Similarly, documents can be made private by placing them in a collection with appropriate privacy settings (see Image / document permissions). Private pages and documents work on Wagtail out of the box - the site implementer does not need to do anything to set them up. However, the default “log in” and “password required” forms are only bare-bones HTML pages, and site implementers may wish to replace them with a page customised to their site design.
122 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Setting up a login page
The basic login page can be customised by setting WAGTAIL_FRONTEND_LOGIN_TEMPLATE to the path of a template you wish to use:
Wagtail uses Django’s standard django.contrib.auth.views.LoginView view here, and so the context variables available on the template are as detailed in Django's login view documentation. If the stock Django login view is not suitable - for example, you wish to use an external authentication system, or you are integrating Wagtail into an existing Django site that already has a working login view - you can specify the URL of the login view via the WAGTAIL_FRONTEND_LOGIN_URL setting:
WAGTAIL_FRONTEND_LOGIN_URL='/accounts/login/'
To integrate Wagtail into a Django site with an existing login mechanism, setting WAGTAIL_FRONTEND_LOGIN_URL = LOGIN_URL will usually be sufficient.
Setting up a global “password required” page
By setting PASSWORD_REQUIRED_TEMPLATE in your Django settings file, you can specify the path of a template which will be used for all “password required” forms on the site (except for page types that specifically override it - see below):
This template will receive the same set of context variables that the blocked page would pass to its own template via get_context() - including page to refer to the page object itself - plus the following additional variables (which override any of the page’s own context variables of the same name): • form - A Django form object for the password prompt; this will contain a field named password as its only vis- ible field. A number of hidden fields may also be present, so the page must loop over form.hidden_fields if not using one of Django’s rendering helpers such as form.as_p. • action_url - The URL that the password form should be submitted to, as a POST request. A basic template suitable for use as PASSWORD_REQUIRED_TEMPLATE might look like this:
Password required
Password required
You need a password to access this page.
Password restrictions on documents use a separate template, specified through the setting DOCUMENT_PASSWORD_REQUIRED_TEMPLATE; this template also receives the context variables form and action_url as described above.
Setting a “password required” page for a specific page type
The attribute password_required_template can be defined on a page model to use a custom template for the “password required” view, for that page type only. For example, if a site had a page type for displaying embedded videos along with a description, it might choose to use a custom “password required” template that displays the video description as usual, but shows the password form in place of the video embed.
As standard, Wagtail organises panels for pages into three tabs: ‘Content’, ‘Promote’ and ‘Settings’. For snippets Wagtail puts all panels into one page. Depending on the requirements of your site, you may wish to customise this for specific page types or snippets - for example, adding an additional tab for sidebar content. This can be done by specifying an edit_handler attribute on the page or snippet model. For example:
from wagtail.admin.edit_handlers import TabbedInterface, ObjectList class BlogPage(Page): # field definitions omitted
Wagtail provides a general-purpose WYSIWYG editor for creating rich text content (HTML) and embedding media such as images, video, and documents. To include this in your models, use the RichTextField function when defining a model field:
from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class BookPage(Page): body= RichTextField()
RichTextField inherits from Django’s basic TextField field, so you can pass any field parameters into RichTextField as if using a normal Django field. This field does not need a special panel and can be defined with FieldPanel. However, template output from RichTextField is special and needs to be filtered in order to preserve embedded content. See Rich text (filter).
Limiting features in a rich text field
By default, the rich text editor provides users with a wide variety of options for text formatting and inserting embedded content such as images. However, we may wish to restrict a rich text field to a more limited set of features - for example: • The field might be intended for a short text snippet, such as a summary to be pulled out on index pages, where embedded images or videos would be inappropriate; • When page content is defined using StreamField, elements such as headings, images and videos are usually given their own block types, alongside a rich text block type used for ordinary paragraph text; in this case, allowing headings and images to also exist within the rich text content is redundant (and liable to result in inconsistent designs). This can be achieved by passing a features keyword argument to RichTextField, with a list of identifiers for the features you wish to allow:
The feature identifiers provided on a default Wagtail installation are as follows: • h1, h2, h3, h4, h5, h6 - heading elements • bold, italic - bold / italic text • ol, ul - ordered / unordered lists
• hr - horizontal rules • link - page, external and email links • document-link - links to documents • image - embedded images • embed - embedded media (see Embedded content) We have few additional feature identifiers as well. They are not enabled by default, but you can use them in your list of identifiers. These are as follows: • code - inline code • superscript, subscript, strikethrough - text formatting • blockquote - blockquote The process for creating new features is described in the following pages: • Rich text internals • Extending the Draftail Editor • Extending the Hallo Editor
Image Formats in the Rich Text Editor
On loading, Wagtail will search for any app with the file image_formats.py and execute the contents. This pro- vides a way to customise the formatting options shown to the editor when inserting images in the RichTextField editor. As an example, add a “thumbnail” format:
# image_formats.py from wagtail.images.formats import Format, register_image_format register_image_format(Format('thumbnail','Thumbnail','richtext-image thumbnail',
˓→'max-120x120'))
To begin, import the Format class, register_image_format function, and optionally unregister_image_format function. To register a new Format, call the register_image_format with the Format object as the argument. The Format class takes the following constructor arguments: name The unique key used to identify the format. To unregister this format, call unregister_image_format with this string as the only argument. label The label used in the chooser form when inserting the image into the RichTextField. classnames The string to assign to the class attribute of the generated tag.
Note: Any class names you provide must have CSS rules matching them written separately, as part of the front end CSS code. Specifying a classnames value of left will only ensure that class is output in the generated markup, it won’t cause the image to align itself left.
filter_spec The string specification to create the image rendition. For more, see the How to use images in templates. To unregister, call unregister_image_format with the string of the name of the Format as the only argument.
126 Chapter 1. Index Wagtail Documentation, Release 2.15a0
Warning: Unregistering Format objects will cause errors viewing or editing pages that reference them.
Customising generated forms class wagtail.admin.forms.WagtailAdminModelForm class wagtail.admin.forms.WagtailAdminPageForm Wagtail automatically generates forms using the panels configured on the model. By default, this form subclasses WagtailAdminModelForm, or WagtailAdminPageForm for pages. A custom base form class can be con- figured by setting the base_form_class attribute on any model. Custom forms for snippets must subclass WagtailAdminModelForm, and custom forms for pages must subclass WagtailAdminPageForm. This can be used to add non-model fields to the form, to automatically generate field content, or to add custom validation logic for your models: from django import forms from django.db import models import geocoder # not in Wagtail, for example only - https://geocoder.readthedocs.io/ from wagtail.admin.edit_handlers import FieldPanel from wagtail.admin.forms import WagtailAdminPageForm from wagtail.core.models import Page class EventPageForm(WagtailAdminPageForm): address= forms.CharField()
def clean(self): cleaned_data= super().clean()
# Make sure that the event starts before it ends start_date= cleaned_data['start_date'] end_date= cleaned_data['end_date'] if start_date and end_date and start_date> end_date: self.add_error('end_date','The end date must be after the start date')
Wagtail will generate a new subclass of this form for the model, adding any fields defined in panels or content_panels. Any fields already defined on the model will not be overridden by these automatically added fields, so the form field for a model field can be overridden by adding it to the custom form.
Customising admin templates
In your projects with Wagtail, you may wish to replace elements such as the Wagtail logo within the admin interface with your own branding. This can be done through Django’s template inheritance mechanism. You need to create a templates/wagtailadmin/ folder within one of your apps - this may be an existing one, or a new one created for this purpose, for example, dashboard. This app must be registered in INSTALLED_APPS before wagtail.admin:
INSTALLED_APPS=( # ...
'dashboard',
'wagtail.core', 'wagtail.admin',
# ... )
Custom branding
The template blocks that are available to customise the branding in the admin interface are as follows:
branding_logo
To replace the default logo, create a template file dashboard/templates/wagtailadmin/base.html that overrides the block branding_logo:
128 Chapter 1. Index Wagtail Documentation, Release 2.15a0
The logo also appears on the admin 404 error page; to replace it there too, create a template file dashboard/ templates/wagtailadmin/404.html that overrides the branding_logo block. The logo also appears on the wagtail userbar; to replace it there too, create a template file dashboard/templates/ wagtailadmin/userbar/base.html that overwrites the branding_logo block. branding_favicon
To replace the favicon displayed when viewing admin pages, create a template file dashboard/templates/ wagtailadmin/admin_base.html that overrides the block branding_favicon:
To replace the title prefix (which is ‘Wagtail’ by default), create a template file dashboard/templates/ wagtailadmin/admin_base.html that overrides the block branding_title:
To replace the login message, create a template file dashboard/templates/wagtailadmin/login.html that overrides the block branding_login:
{% extends "wagtailadmin/login.html" %}
{% block branding_login %}Sign in to Frank's Site{% endblock %}
branding_welcome
To replace the welcome message on the dashboard, create a template file dashboard/templates/ wagtailadmin/home.html that overrides the block branding_welcome:
{% extends "wagtailadmin/home.html" %}
{% block branding_welcome %}Welcome to Frank's Site{% endblock %}
Warning: CSS variables are not supported in Internet Explorer, so the admin will appear with the default colors when viewed in that browser. The default Wagtail colors conform to the WCAG2.1 AA level color contrast requirements. When customizing the admin colors you should test the contrast using tools like Axe.
To customize the primary color used in the admin user interface, inject a CSS file using the hook in- sert_global_admin_css and override the variables within the :root selector:
:root { --color-primary-hue: 25; } color-primary is an hsl color composed of 3 CSS variables - --color-primary-hue (0-360 with no unit), --color-primary-saturation (a percentage), and --color-primary-lightness (also a percentage). Separating the color into 3 allows us to calculate variations on the color to use alongside the primary color. If needed, you can also control those variations manually by setting hue, saturation, and lightness variables for the following colors: color-primary-darker, color-primary-dark, color-primary-lighter, color-primary-light, color-input-focus, and color-input-focus-border:
The admin interface has a number of variables available to the renderer context that can be used to customize the branding in the admin page. These can be useful for customizing the dashboard on a multitenanted Wagtail installation:
130 Chapter 1. Index Wagtail Documentation, Release 2.15a0 root_page
Returns the highest explorable page object for the currently logged in user. If the user has no explore rights, this will default to None. root_site
Returns the name on the site record for the above root page. site_name
Returns the value of root_site, unless it evaluates to None. In that case, it will return the value of settings. WAGTAIL_SITE_NAME. To use these variables, create a template file dashboard/templates/wagtailadmin/home.html, just as if you were overriding one of the template blocks in the dashboard, and use them as you would any other Django template variable:
{% extends "wagtailadmin/home.html" %}
{% block branding_welcome %}Welcome to the Admin Homepage for {{ root_site }}{%
˓→endblock %}
Extending the login form
To add extra controls to the login form, create a template file dashboard/templates/wagtailadmin/ login.html. above_login and below_login
To add content above or below the login form, override these blocks:
{% extends "wagtailadmin/login.html" %}
{% block above_login %} If you are not Frank you should not be here! {% endblock %} fields
To add extra fields to the login form, override the fields block. You will need to add {{ block.super }} somewhere in your block to include the username and password fields:
To add extra buttons to the login form, override the submit_buttons block. You will need to add {{ block. super }} somewhere in your block to include the sign in button:
{% extends "wagtailadmin/login.html" %}
{% block submit_buttons %} {{ block.super }}
˓→up' %} {% endblock %}
login_form
To completely customise the login form, override the login_form block. This block wraps the whole contents of the